In C, 0.55 == 0.55f
is false while 0.5 == 0.5f
is true. Why is it different?
Comparing 0.55
:
#include <stdio.h>
int main() {
if (0.55 == 0.55f)
printf("Hi");
else
printf("Hello");
}
Outputs Hello
.
Comparing 0.5
:
#include <stdio.h>
int main() {
if (0.5 == 0.5f)
printf("Hi");
else
printf("Hello");
}
Outputs Hi
.
For both the code snippets, I expected Hello
.
Why this difference?
0.5
is a dyadic rational and of an appropriate magnitude so 0.5
is exactly one-half either as a float
or a double
.
The same cannot be said for 0.55
. A double
will store that number with no less precision than a float
, and most likely more.
In both cases, the float
is implicitly converted to a double
prior to ==
, but by then any truncation has taken place.