在示例中,为什么将float转换为int打印不同的结果?

时间:2018-09-05 09:26:10

标签: c

#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是正确的输出,请告诉我为什么。

1 个答案:

答案 0 :(得分:5)

在单精度IEEE754(最可能在您的平台上使用的float方案)中,x3.7999999523162841796875,而y5.19999980926513671875。它们的总和不到9,并且对int的强制转换会截断结果。 (请注意,float x = 3.8实际上将double常量3.8截断为float3.8f是类型float的常量。)

但是3.8 + 5.2的计算精度为 double 。在双精度IEEE754中,3.83.799999999999999822364316059974953532218933105468755.25.20000000000000017763568394002504646778106689453125。总和刚刚超过9,因此int截断恢复了9。

ab不同的事实是由于对编译器的浮点运算没有 strict 。您应该可以更改其设置。

相关问题