C中的浮动比较

Anu*_*arg 1 c floating-point precision if-statement compiler-errors

#include<stdio.h>
int main()
{
    float x = 0.6;
    if (x == 0.6)
        printf("IF");
    else if (x == 0.6f)
        printf("ELSE IF");
    else
        printf("ELSE");
}
Run Code Online (Sandbox Code Playgroud)

此代码提供输出ELSE IF

#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");
}
Run Code Online (Sandbox Code Playgroud)

此代码提供输出IF

尽管两个程序看起来都相同,但为什么输出有差异?为什么会这样?

oua*_*uah 6

因为0.5具有IEEE-754二进制格式(如binary32和binary64)的精确表示. 0.5是两个负面的力量.0.6另一方面,它不是两个的力量,它不能完全用float或表示double.