This question already has an answer here:
- Is floating point math broken? 27 answers
#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".
Aucun commentaire:
Enregistrer un commentaire