为什么输出不同于我预期的代码? [英] why output is different from the code I expected?
问题描述
我运行此代码,但输出与我预期的不同。
输出:
c = 1324
v = 1324.99
我预计输出应该是 v
的1324.987。为什么 v
中的数据与输出不同?
我在windows 8 32上使用代码lite
#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;
}
cout
为6,因此只显示6个小数位。数字四舍五入到最接近的值,这就是为什么你看到1324.99。您需要设置更高的精度才能查看更正确的值
但是,设置精度太高可能会打印出大量的垃圾数字,因为二进制浮点类型不能精确存储所有十进制浮点值。 p>
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;
}
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.
这篇关于为什么输出不同于我预期的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!