#include <stdio.h>
#include <float.h>
#include <stdlib.h>
int main() {
float x = 3.8, y = 5.2;
int a, b, c;
float d = x + y;
a = d;
b = (int)(x + y);
c = (int)(3.8 + 5.2);
printf("a=%d,b=%d,c=%d\n", a, b, c);
return 0;
}
结果是
9,8,9
我认为9,9,9
是正确的输出,请告诉我为什么。
答案 0 :(得分:5)
在单精度IEEE754(最可能在您的平台上使用的float
方案)中,x
是3.7999999523162841796875
,而y
是5.19999980926513671875
。它们的总和不到9,并且对int
的强制转换会截断结果。 (请注意,float x = 3.8
实际上将double
常量3.8
截断为float
:3.8f
是类型float
的常量。)
但是3.8 + 5.2
的计算精度为 double 。在双精度IEEE754中,3.8
为3.79999999999999982236431605997495353221893310546875
,5.2
为5.20000000000000017763568394002504646778106689453125
。总和刚刚超过9,因此int
截断恢复了9。
a
和b
不同的事实是由于对编译器的浮点运算没有 strict 。您应该可以更改其设置。