英文:
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 值被隐式转换为 float。float 和 double 类型具有不同的精度,因此转换会导致小的四舍五入误差。因此,存储在 f 中的 float 值不等于 0.1 的 double 值。
如果你在出现的两个地方都将 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”.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论