float f = 0.7;
if( f == 0.7 )
printf("equal");
else
printf("not equal");
Why output is -> not equal ????
Why is happens so ?
float f = 0.7;
if( f == 0.7 )
printf("equal");
else
printf("not equal");
Why output is -> not equal ????
Why is happens so ?
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
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
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.