C中浮点比较的奇怪输出

时间:2014-08-27 12:17:19

标签: c floating-point floating-accuracy floating-point-precision

代码1

#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");
}   

输出:ELSE IF

代码2

#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");
}

输出:IF

为什么输出会出现这样的差异?我知道变量'x'将被提升为'double'类型,'0.1'和'0.5'将被提升为'double'类型。但是,我不明白为什么Code 2的输出没有输出ELSE IF。感谢。

0 个答案:

没有答案