Monday, 6 June 2016

c - Why the control goes in “else” part?











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

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...