Possible Duplicate:
strange output in comparision of float with float literal
float a = 0.7;
if (a < 0.7) ;
Why does the expression here evaluate to true?
Possible Duplicate:
strange output in comparision of float with float literal
float a = 0.7;
if (a < 0.7) ;
Why does the expression here evaluate to true?
Because 0.7 can't be exactly represented as a float or double. When you store it in a float it is rounded down a little further than when it's represented as a double (the default).
Floating point numbers have limited precision. 0.7 most likely can't be exactly represented, so the value in a might be 0.6999999999982 or so in a float. This compared to a double 0.7 (which is more precise: 0.6999999999999999999999999384) will show that it is less.
Check this out: http://docs.sun.com/source/806-3568/ncg_goldberg.html
Because the literal 0.7 is of type double, not float. The actual value of a is 0.699999... Fix:
if (a < 0.7f)
The other answers hint at it, but this issue is caused by you not adding an "f" to your numbers.
Any number with a decimal point will be implicitly interpreted as a double by the compiler (i.e. a 64-bit value with twice as much precision as a float). In your first line, you assign a double to a float, thereby losing precision (if you had warnings turned on, which you should have, you would have gotten a compiler warning).
In the second line, you're comparing a float to a double. The float will be promoted to a double (correct me if I'm wrong), so you have the less precise version of 0.7 compared to the more precise 0.7.
Solution: ALWAYS use "f" when dealing with floats, i.e.
float a = 0.7f;
if (a < 0.7f);
Try this:
float a = 0.7f;
if (fabs(a - 0.7f) < numeric_limits<float>::epsilon) ;
More details at most effective way for float and double comparison.
Read this: What Every Computer Scientist Should Know About Floating-Point Arithmetic
Every computer programmer must know this.