#include <stdio.h>
int main()
{
float f;
f = 0.4;
if(f<0.4)
printf("It is less");
if(f>0.4)
printf("It is greater");
if(f==0.4)
printf("It is equal");
}
I am not able to get why the output is showing "It is greater".
I get that 0.4 converted to binary representation is 0x3ECCCCCD, which is 4.000000059604644775390625E-1. The doubt is if f stores this rounded value, why 0.4 in the comparison is exact. If both f and 0.4 gets rounded, the output should have been "It is equal".
I tried with f = 0.5, it is showing "It is equal".
While f=0.9, it is showing "It is less".
Please take note that there is no arithmetic at all.
While
fis afloat, all your literals aredouble.If you ask nicely, the compiler will even warn you about the assignment:
Unfortunately, it cannot warn about the comparison, because simply widening the smaller type is nearly always what you want, and was thus codified.
Anyway, floating-point math is dangerous and surprising for the uninitiated:
Is floating point math broken?