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.7
is a double.
You've stored that in a float, which might have less precision than a double, thus the me == 1.7
is comparing 1.7 as a float(promoted to a double) to 1.7 as a double.
In this case, me == 1.7f
should make them compare as equal, or changing me
to a double double me = 1.7;
In the general case though, you'd want equality to be compared using an epsilon as @duffymo shows.
Also, Obligatory read.
Here is some reading material What Every Computer Scientist Should Know About Floating-Point Arithmetic
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With