Float comparison in C

271 Views Asked by At
#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");
}

This code gives output 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");
}

This code gives output IF

Even though both the programs looks same but why there is difference in the outputs? Why this is happening?

1

There are 1 best solutions below

7
On BEST ANSWER

Because 0.5 has an exact representation in IEEE-754 binary formats (like binary32 and binary64). 0.5 is a negative power of two. 0.6 on the other hand is not a power of two and it cannot be represented exactly in float or double.