Possible Duplicate:
strange output in comparision of float with float literal
#include<stdio.h>
int main()
{
float me = 1.7;
if(me==1.7)
printf("C");
else
printf("C++");
}
Output: C++
Now the reason for this behaviour is said that many floating point numbers cant be represented with absolute precision in binary.
My question is that – If computer thinks and manipulates in binary. Any uncertanity in representation of me would be same for 1.7 when compared. So both should be equal.
ALso how typecasting solves this problem? (float)1.7
You are comparing a float to a double. the literal
1.7is a double.You’ve stored that in a float, which might have less precision than a double, thus the
me == 1.7is comparing 1.7 as a float(promoted to a double) to 1.7 as a double.In this case,
me == 1.7fshould make them compare as equal, or changingmeto a doubledouble me = 1.7;In the general case though, you’d want equality to be compared using an epsilon as @duffymo shows.
Also, Obligatory read.