【发布时间】:2016-11-11 17:18:27
【问题描述】:
请看下面的程序
#include<stdio.h>
int main()
{
float x = 0.1;
if (x == 0.1)
printf("IF");
else if (x == 0.1f)
printf("ELSE IF");
else
printf("ELSE");
}
这里还有一个程序
#include<stdio.h>
int main()
{
float x = 0.5;
if (x == 0.5)
printf("IF");
else if (x == 0.5f)
printf("ELSE IF");
else
printf("ELSE");
}
从这两个程序中,我们期望得到相似的结果,因为两者都没有发生任何变化,一切都相同,并且比较项也相应地发生了变化。
但上述 2 个程序会产生不同的结果
第一个节目
ELSE
第二个节目
IF
为什么这两个程序的行为不同
【问题讨论】:
-
您正在比较
floats。你绝对应该看看这个:stackoverflow.com/questions/17404513/…
标签: c++ c comparison type-conversion