I could be mistaken, but I suspect it's because the floating point representation of 7.07 isn't quite exact. If you try different constants (1.0, 1.1, 2.0, 2.1) you'll get varying degrees of accuracy. Also, in gcc at least, it works differently when comparing two variables rather than a variable and a literal; this can be demostrated with the following program:
Code: Select all
#include <stdio.h>
void compare (float x, float y);
main()
{
float a[8] = {0.09, 0.9, 1.0, 2.0, 2.1, 2.1478, 3.0, 4.0};
compare (a[0], 0.09);
if(a[0] == 0.09)
printf("%f == %f\n", a[0], 0.09);
else if(a[0] < 0.09)
printf("%f < %f\n", a[0], 0.09);
else
printf("%f > %f\n", a[0], 0.09);
printf("\n");
compare (a[1], 0.9);
if(a[1] == 0.9)
printf("%f == %f\n", a[1], 0.9);
else if(a[0] < 0.9)
printf("%f < %f\n", a[1], 0.9);
else
printf("%f > %f\n", a[1], 0.9);
printf("\n");
compare (a[2], 1.0);
if(a[2] == 1.0)
printf("%f == %f\n", a[2], 1.0);
else if(a[2] < 1.0)
printf("%f < %f\n", a[2], 1.0);
else
printf("%f > %f\n", a[2], 1.0);
printf("\n");
compare (a[3], 2.0);
if(a[3] == 2.0)
printf("%f == %f\n", a[3], 2.0);
else if(a[3] < 2.0)
printf("%f < %f\n", a[3], 2.0);
else
printf("%f > %f\n", a[3], 2.0);
printf("\n");
compare (a[4], 2.1);
if(a[4] == 2.1)
printf("%f == %f\n", a[4], 2.1);
else if(a[4] < 2.1)
printf("%f < %f\n", a[4], 2.1);
else
printf("%f > %f\n", a[4], 2.1);
printf("\n");
compare (a[5], 2.1478);
if(a[5] == 2.1478)
printf("%f == %f\n", a[5], 2.1478);
else if(a[5] < 2.1478)
printf("%f < %f\n", a[5], 2.1478);
else
printf("%f > %f\n", a[5], 2.1478);
printf("\n");
compare (a[6], 3.0);
if(a[6] == 3.0)
printf("%f == %f\n", a[6], 3.0);
else if(a[6] < 3.0)
printf("%f < %f\n", a[6], 3.0);
else
printf("%f > %f\n", a[6], 3.0);
printf("\n");
compare (a[7], 4.0);
if(a[7] == 4.0)
printf("%f == %f\n", a[7], 4.0);
else if(a[7] < 4.0)
printf("%f < %f\n", a[7], 4.0);
else
printf("%f > %f\n", a[7], 4.0);
printf("\n");
getchar();
}
void compare (float x, float y)
{
if( x == y)
printf("%f == %f\n", x, y);
else if(x < y)
printf("%f < %f\n", x, y);
else
printf("%f > %f\n", x, y);
}
The same comparisons are done each time, but whereas the variable to variable comparisons always come out equal, the variable to literal ones are only equal if the literal have an exact representation in binary floating point.
At least, that's my thoughts on it. C&CW.