Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

less than (<) comparison of float with if statement in c [duplicate]

case 1

float a = 0.6;

if (a < 0.6)
{
    printf("c");
}
else
{
    printf("c#");
}

output c#

case 2

float a = 0.9;

if (a < 0.9)
{
    printf("c");
}
else
{
    printf("c#");
}

output c

now question is why ?

like image 641
Dios Avatar asked Jun 02 '14 19:06

Dios


1 Answers

I'm assuming float is IEEE 754 32-bit binary, and double is IEEE 754 64-bit binary.

The closest double to 0.6, the actual value of the literal, is 0.59999999999999997779553950749686919152736663818359375. The result of converting it to float is 0.60000002384185791015625, slightly bigger.

The closest double to 0.9 is 0.90000000000000002220446049250313080847263336181640625. The result of converting it to float is 0.89999997615814208984375, slightly smaller.

In each case, a decimal fraction that cannot be represented exactly is rounded to the nearest double to represent the literal. It is rounded to a float for assignment to a, which under round-to-nearest rules may be slightly smaller or slightly greater than the double, or even could be exactly the same if the double's binary representation had a lot of trailing zeros.

like image 79
Patricia Shanahan Avatar answered Oct 07 '22 03:10

Patricia Shanahan