Why is the output different from what I expected?

混江龙づ霸主 提交于 2019-12-13 05:05:00

问题


I run this code but the output was different from what I expected. The output:

c = 1324
v = 1324.99

I expected that the output should be 1324.987 for v. Why is the data in v different from output?

I'm using code lite on Windows 8 32.

#include <iostream>
using namespace std;
int main()
{
    double v = 1324.987;
    int n;
    n = int (v);
    cout << "c = " << n << endl;
    cout << "v = " << v << endl;
    return 0;
}

回答1:


The default precision when printing with cout is 6, so only 6 decimal places will be displayed. The number is rounded to the nearest value, that's why you saw 1324.99. You need to set a higher precision to see the more "correct" value

However, setting the precision too high may print out a lot of garbage digits behind, because binary floating-point types cannot store all decimal floating-point values exactly.




回答2:


Floating point types inherit rounding errors as a result of their fixed width representations. For more information, see What Every Computer Scientist Should Know About Floating-Point Arithmetic.



来源:https://stackoverflow.com/questions/30953973/why-is-the-output-different-from-what-i-expected

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!