0

While execute this step am getting the value from If actually it should be from else

#include<stdio.h>
void main()
{
 float a=0.9;
 clrscr();
 if(a<0.9)
  printf("value from if a %f",a);
 else
  printf("value from else a %f",a);
getch();

}

output for the above code is from If.

Just check the below code, this will output correctly to else part

#include<stdio.h>
void main()
{
 float a=0.8;
 clrscr();
 if(a<0.8)
  printf("value from if a %f",a);
 else
  printf("value from else a %f",a);
 getch();
}

output for the above code is from else.

I tried with 0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9

0.7,0.9 only goes to if others goes to else.

Kindly explain this variation.

Damien
  • 1,490
  • 1
  • 8
  • 17
Vinoth Kumar
  • 413
  • 6
  • 18
  • *What Every Computer Scientist Should Know About Floating Point* (http://docs.sun.com/source/806-3568/ncg_goldberg.html) -- and the other answers in http://stackoverflow.com/questions/4664662/understanding-floating-point-problems – Jongware Oct 23 '13 at 09:16

1 Answers1

0

Floating points are stored as in powers of 2 as per IEEE format. It is a common problem with comparison of floating point numbers.

Try changing your code with adding .f

#include<stdio.h>
void main()
{
 float a=0.9f;
 clrscr();
 if(a<0.9f)
  printf("value from if a %f",a);
 else
  printf("value from else a %f",a);
getch();

}

Otherwise you need to have how much precision for your comparison. Either you can have delta (const float delta = 0.000001;) and add / subtract this value with your comparison. Like given on the page:

http://www.softwareandfinance.com/CPP/FAQ_Floating_Point.html