I worked out the following code and got a bizarre output. Can anyone explain how it works?
main()
{
float a=0.8;
float b=0.25;
if(a==0.8)
printf("HELLO")
if(b==0.25)
printf("WORLD")
}
And the output that I got is surprisingly
WORLD
thanks in advance
This is because 0.25 is a power of two (i.e. 2^-2), while 0.8 is not. Only exact sums of powers of two can be represented exactly; all other numbers, including 0.8, are represented as an approximation, which has a different precision between float
and double
. The 0.8
in a==0.8
is a double
, while a
is a float
. Their representations are different, and so are their values.