1
#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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Anuj Garg
  • 584
  • 7
  • 22

1 Answers1

6

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.

ouah
  • 142,963
  • 15
  • 272
  • 331
  • Did you just happen to know that ? – Utsav T Jun 20 '15 at 10:14
  • @Noob I'm affraid I don't understand your question. – ouah Jun 20 '15 at 10:15
  • The answer was pretty amazing. That's it ! I was wondering how you knew it. – Utsav T Jun 20 '15 at 10:16
  • Sorry ouah I did not understood your point. Can you please elaborate? – Anuj Garg Jun 20 '15 at 10:18
  • @AnujGarg numbers `0.5`, `0.25`, `0.125`, etc. are negative power of two and therefore can be represented without representation errors in `float` and `double`. To get more information on floating points I can suggest you to read http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html – ouah Jun 20 '15 at 10:20
  • @AnujGarg - Try representing 0.5 in binary. And then try the same for 0.6. You'll get the point. – Utsav T Jun 20 '15 at 10:20
  • @Noob well I think I consider this fact some of the basics of IEEE-754 but floating point is a broad and not easy subject. – ouah Jun 20 '15 at 10:21