浮点舍入误差
输出是
x=1000300 y=1000000, z=1000300
我可以理解如何得到 x 和 z 但 c's y 的输出没有意义。
#include <stdio.h>
int main()
{ int i=0;
float a = 100;
a = a*a*a*a*a;
float c = 3;
float x = 1000000*c + a;
float y = a;
float z = 0;
for (i=0; i<1000000; i++)
{ y += c;
z += c;
}
z += a;
x /= 10000;
y /= 10000;
z /= 10000;
printf("x=%.0f y=%.0f, z=%.0f\n", x, y, z);
}
The output is
x=1000300 y=1000000, z=1000300
I can understand how I got x and z but c's y's output makes no sense.
#include <stdio.h>
int main()
{ int i=0;
float a = 100;
a = a*a*a*a*a;
float c = 3;
float x = 1000000*c + a;
float y = a;
float z = 0;
for (i=0; i<1000000; i++)
{ y += c;
z += c;
}
z += a;
x /= 10000;
y /= 10000;
z /= 10000;
printf("x=%.0f y=%.0f, z=%.0f\n", x, y, z);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
y
中的值从 1E10 开始(从对a
的赋值开始)。你将 3 加一百万次。问题在于
float
最多有 7 位有效十进制数字,因此您实际上不会每次都更改y
,因此除以 10,000 的结果是10,000,000< /s> 显示为 1,000,000。如果您使用
double
对其进行编码,您会看到更接近您期望的结果。The value in
y
starts out at 1E10 (from the assignment toa
). You add 3 to this a million times.The trouble is that a
float
has at most 7 significant decimal digits, so you effectively do not changey
each time, hence the result divided by 10,000 is10,000,0001,000,000 as displayed.If you coded it with
double
, you would see more nearly the result you expect.