Comparing Same Float Values In C
strange output in comparison of float with float literal
Float addition promoted to double?
I read the above links on floating points, but even getting strange output.
#include<stdio.h>
int main()
{
float x = 0.5;
if (x == 0.5)
printf("IF");
else if (x == 0.5f)
printf("ELSE IF");
else
printf("ELSE");
}
Now, according to the promotion rules, Shouldn't "ELSE IF" must be printed ?
But, here it is printing "IF"
EDIT : Is it because 0.5 = 0.1 in binary and everything is 0 after that and loss of precision hence no effects, so comparison IF returns true.
Had it been 0.1, 0.2, 0.3, 0.4, 0.6, 0.7.... , then Else If block returns true.
Pardon me asking same question, because I have read from the above links that floats comparison must never be done.
But, What is the reason of this unexpected behaviour ?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…