Possible Duplicate:
strange output in comparison of float with float literal
When I am trying to compare 2 same float values it doesn’t print “equal values” in the following code :
void main()
{
float a = 0.7;
clrscr();
if (a < 0.7)
printf("value : %f",a);
else if (a == 0.7)
printf("equal values");
else
printf("hello");
getch();
}
Thanks in advance.
While many people will tell you to always compare floating point numbers with an epsilon (and it’s usually a good idea, though it should be a percentage of the values being compared rather than a fixed value), that’s not actually necessary here since you’re using constants.
Your specific problem here is that:
uses the double constant
0.7to create a single precision number (losing some precision) while:will compare two double precision numbers (
ais promoted first).The precision that was lost when turning the double
0.7into the floatais not regained when promotingaback to a double.If you change all those
0.7values to0.7f(to force float rather than double), or if you just makeaa double, it will work fine – I rarely usefloatnowadays unless I have a massive array of them and need to save space.You can see this in action with:
which will output something like (slightly modified to show difference):