在c++ Windows中替代lprint

C++ Windows alternative to lrint?

本文关键字:lprint c++ Windows      更新时间:2023-10-16

windows中C99 lprint函数的正确替代方案是什么?

#define lrint(x) (floor(x+(x>0) ? 0.5 : -0.5)) 
/* and if fesetround(0) behavior is required*/
#define lrint(x) ((int)(x))  

正确吗?

没有执行C99标准定义的行为的lrint的[简单]单一定义。这是因为lrint的行为是由对fesetround的单独调用控制的。相反,您应该使用单独的四舍五入函数,保证应用程序所需行为的语义。

floor(x+(x>0) ? 0.5 : -0.5)

将只正确舍入正数,但不是负数,因为floor()将舍入到负无穷,这意味着floor(-7.1)=-8,而引用的代码段并不能解决这个问题:floor(-7.1-0.5)仍然=-8,而正确舍入到最接近的整数必须导致-7。下面的代码可以正确舍入:

return int(x + ((x >= 0.0) ? 0.5 : -0.5));

或者

return ((x >= 0.0) ? floor(x+0.5) : ceil(x-0.5));