这段代码为什么打印出 “False”?为什么不打印出 “True”?

huangapple go评论74阅读模式
英文:

Why dpes this code print "False"? Why doesn't it print "True"?

问题

当我运行这段代码时,它打印出 False。我期望这段代码输出 True 而不是 False

英文:

When I run this code it prints False. it's not clear to me

#include <stdio.h>
    int main()
    {
        float f = 0.1;
        if (f == 0.1)
            printf("True");
        else
            printf("False");
    }

I expect this code to print out True instead of False

答案1

得分: 5

0.1 是一个 double 常量。在 float f = 0.1; 中,double 值被隐式转换为 floatfloatdouble 类型具有不同的精度,因此转换会导致小的四舍五入误差。因此,存储在 f 中的 float 值不等于 0.1double 值。

如果你在出现的两个地方都将 0.1 更改为 0.1f,程序将输出“True”。

英文:

0.1 is a double constant. In float f = 0.1;, the double value is implicit converted to float. The float and double types have different precisions, so the conversion incurs a small rounding error. In consequence, the float value stored in f is not equal to the double value of 0.1.

If you change 0.1 to 0.1f in both places it appears, the program will print “True”.

huangapple
  • 本文由 发表于 2023年3月7日 06:15:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75656340.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定