1

Possible Duplicate:
Floating point comparison

#include<stdio.h>
#include<conio.h>
int main()
{
float i=0.7;
clrscr();
if(i < 0.7)
     printf("If Block");
else
     printf("Else Block");
getch();
return 0;
}

I dont understand whay the output will be "If block".....please help why the if part is executed?

Community
  • 1
  • 1
Harshil Shah
  • 353
  • 4
  • 9
  • 18
  • Use either `double` or `0.7f`. – Yakov Galka Nov 27 '12 at 18:21
  • 3
    Spend an hour or so and read [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). It will be a real eye-opener if you're fuzzy on floating point approximation. – WhozCraig Nov 27 '12 at 18:22

1 Answers1

13

Actually i is 0.69999999998 in it's floating representation.

When you assign i=0.7 in memory 0.7 cannot be represented in double precision as you would have thought.

So the comparison between float and double leads to type promotion and in that case i is less than 0.7 which is double.

gsamaras
  • 69,751
  • 39
  • 173
  • 279
Omkant
  • 8,730
  • 7
  • 37
  • 59
  • shouldn't 0.7 always round to the same value, causing the comparison to consistently fail? – John Dvorak Nov 27 '12 at 18:21
  • 3
    @JanDvorak: no, the comparison is between a `float` and a `double`, so the `float` is promoted and compared as `double`. – Yakov Galka Nov 27 '12 at 18:22
  • 0.7 is by default double – Omkant Nov 27 '12 at 18:23
  • The key ingredient is the implicit double=>float cast that rounds down, then compares to the original double. – John Dvorak Nov 27 '12 at 18:23
  • 1
    @Jan Dvorak: If the original code used `0.7f` instead of just `0.7`, the comparison would fail, since if would indeed be represented identically. But `0.7` by itself is a `double`, which is represented differently than that `float i`. – AnT Nov 27 '12 at 18:27
  • `(double)((float)0.7) != 0.7` -- there's loss of precision in the conversions. – pmg May 08 '17 at 11:52