【发布时间】:2013-08-22 09:58:22
【问题描述】:
找不到下面这段代码的原因:
#include <stdio.h>
int main()
{
float f = 0.1;
if (f == 0.1)
printf("True");
else
printf("False");
return 0;
}
输出为假。
#include <stdio.h>
int main()
{
float f = 0.1;
if (f == (float)0.1)
printf("True");
else
printf("False");
return 0;
}
现在显示正确的输出。这背后的原因是什么?
还有这种行为的原因是什么。
#include <stdio.h>
main()
{
int n = 0, m = 0;
if (n > 0)
if (m > 0)
printf("True");
else
printf("False");
}
【问题讨论】:
-
请不要比较浮点数是否相等。浮点数几乎从不相等。
-
复制数十次。
-
..and C tag 开启了今天的“恼人的问题”竞赛,与一个古老的经典。 (信用:Martin James)
-
@H2CO3 感谢您指出这一点。我之前搜索过没有得到相同的结果。我来看看答案。
-
@Megharaj 不客气 - 你也可以从阅读 this 经常被引用的文章中受益。
标签: c floating-point floating-point-conversion