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
  • 363
  • 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
  • 71,951
  • 46
  • 188
  • 305
Omkant
  • 9,018
  • 8
  • 39
  • 59