-3
 int main()   
    {
            float f = 0.1;
            if (f == 0.1)
                printf("True");
            else
                printf("False");
        }

I am just a beginner in c. I don't understand the behavior of the above program. The output is false. Why??

Bathsheba
  • 220,365
  • 33
  • 331
  • 451
Venkat
  • 93
  • 1
  • 7

1 Answers1

7

0.1 is a double literal.

As 0.1 cannot be represented exactly in floating point, a float set to 0.1 will compare false against a double set to 0.1.

Your comparison would behave as intended if you use a float literal: 0.1f (note the suffixed f: not to be confused with your variable name):

float foo /*renamed for clarity*/= 0.1;
if (foo == 0.1f){
     /*this will compare true*/
Bathsheba
  • 220,365
  • 33
  • 331
  • 451
  • might want to add that, if `float` is the desired type, then `float foo = 0.1f;` and `if (foo == 0.1f) puts("True");` would probably be what most people write – Elias Van Ootegem Dec 31 '13 at 10:33
  • @EliasVanOotegem: good point: I've edited. Perhaps a full answer would mention promotion of the floating point type to a double type, but I think that's outside the question scope. – Bathsheba Dec 31 '13 at 10:42