tags:

views:

279

answers:

3
float f = 0.7;
if( f == 0.7 )
    printf("equal");
else
    printf("not equal");

Why output is -> not equal ????

Why is happens so ?

+3  A: 

Wow, this is the third C/C++ question in a row about floating point precision. See http://stackoverflow.com/questions/1839364/float-addition-issue and http://stackoverflow.com/questions/1839225/float-addition-promoted-to-double

Charles Salvia
Everyone saw the first question and started experimenting with what other weirdness they can get?
UncleBens
+20  A: 

This happens because in your statement

  if(f == 0.7)

the 0.7 is treated as a double. Try 0.7f to ensure the value is treated as a float:

  if(f == 0.7f)

Best wishes, Fabian

halfdan
so all literals with decimal point are treated as double ??
Ashish
Yes. The f suffix (as in 0.7f) makes them a float literal.
Timbo
Perhaps more importantly, don't test for exact equality of floating-point values.
Michael Carman
Yes, Michael has proposed the best answer here. You should never be looking for equality between floating point numbers. This answer will only lead to more confusion later on.
Ed Swangren
+4  A: 

This answer to complement the existing ones: note that 0.7 is not representable exactly either as a float (or as a double). If it was represented exactly, then there would be no loss of information when converting to float and then back to double, and you wouldn't have this problem.

It could even be argued that there should be a compiler warning for literal floating-point constants that cannot be represented exactly, especially when the standard is so fuzzy regarding whether the rounding will be made at run-time in the mode that has been set as that time or at compile-time in another rounding mode.

All non-integer numbers that can be represented exactly have 5 as their last decimal. Unfortunately, the converse is not true: some numbers have 5 as their last decimal and cannot be represented exactly. Small integers can all be represented exactly, and division by a power of 2 transforms a number that can be represented into another that can be represented, as long as you do not enter the realm of denormalized numbers.

Pascal Cuoq