int main()
{
float a = 0.8;
if (a == 0.8)
printf("x\n");
else
printf("y\n");
return 0;
}
Though a is equal to 0.8, it outputs y.
Answer
0.8 cannot be represented accurately in binary floating-point. Your code if (a == 0.8)
basically compares single-precision 0.8 with double-precision 0.8, which are not equal.
To see this for yourself, try the following code:
int main()
{
double a = 0.8f;
double b = 0.8;
printf("%lX\n", *(long *)&a);
printf("%lX\n", *(long *)&b);
}
It outputs:
3FE99999A0000000
3FE999999999999A
No comments:
Post a Comment