任何人都可以,请解释为什么舍入0.5
到FE_TONEAREST
所赐0
?它不应该给`1作为结果吗?有没有办法来解决这个问题?
#include <fenv.h>
#include <iostream>
#include <cmath>
int main() {
fesetround(FE_TONEAREST);
std::cout << "Rounding 0.5 to nearest = " << std::rint(0.5) << std::endl;
return 0;
}
coliru上的可运行代码:http ://coliru.stacked-crooked.com/a/9c179ca56f251628
FE_TONEAREST
导致std::rint
将中间情况(±n.5
)舍入到最接近的偶数整数值。0
甚至。
如果要改为使用std::round
此模式,则中途情况会四舍五入“向上”(远离零),这将导致1
。
请参阅的文档std::rint
。
在Mathematica.SE上已解释了为什么需要这种不寻常的舍入形式。(因此您的数据不会全部转移到一个方向)。
顺便说一句,C ++提供了标准标头的正确包装版本,并在std
名称空间中添加了名称(尽管在这里几乎没有关系):#include <cfenv>
而不是#include <fenv.h>
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句