Joh*_*ohn 3 c floating-point rounding floating-accuracy
在试图弄清楚如何将浮子环绕1.255到最近的百分之一时,我发现了一些有趣的东西.我在Debian 6上使用gcc 4.4.5.
int x = (1.255 * 100) + 0.5; // gives me back 125 instead of 126.
float y = (1.255 * 100) + 0.5; // gives me back 126.000000.
Run Code Online (Sandbox Code Playgroud)
为什么当我保存到一个int我回来125而不是126?在fedora中,当我将上面的表达式保存到一个int我回来的时候126.这是debian中的gcc bug吗?任何帮助将不胜感激.谢谢.
虽然这看起来像一个"典型的"浮点问题,但它比这复杂得多.
这个涉及三件事的组合:
让我们打破这个:
double默认情况下,浮点文字属于类型.因此1.255属于类型double.
因此表达式:
(1.255 * 100) + 0.5
Run Code Online (Sandbox Code Playgroud)
是使用类型完成的double.
但由于二进制浮点不能1.255完全表示,表达式的计算结果为:
(1.255 * 100) + 0.5 = 125.99999999999999000000
Run Code Online (Sandbox Code Playgroud)
并且是类型double.
由于这小于126,因此将其存储为整数125.存储它float会将它四舍五入到最近float,这导致126.
int x = (1.255 * 100.) + 0.5;
float y = (1.255 * 100.) + 0.5;
double z = (1.255 * 100.) + 0.5;
cout << fixed;
cout << x << endl;
cout << setprecision(20) << y << endl;
cout << setprecision(20) << z << endl;
Run Code Online (Sandbox Code Playgroud)
输出:
125
126.00000000000000000000
125.99999999999999000000
Run Code Online (Sandbox Code Playgroud)