There are two problems here.
First is that floating point literals like 8.3
have type double
, while a
has type float
. Doubles and floats store values to different precisions, and for values that don't have an exact floating point representation (such as 8.3
), the stored values are slightly different. Thus, the comparison fails.
You could fix this by writing the comparison as a==8.3f
; the f
suffix forces the literal to be a float
instead of a double
.
However, it's bad juju to compare floating point values directly; again, most values cannot be represented exactly, but only to an approximation. If a
were the result of an expression involving multiple floating-point calcuations, it may not be equivalent to 8.3f
. Ideally, you should look at the difference between the two values, and if it's less than some threshold, then they are effectively equivalent:
if ( fabs( a - 8.3f) < EPSILON )
{
// a is "equal enough" to 8.3
}
The exact value of EPSILON
depends on a number of factors, not least of which is the magnitude of the values being compared. You only have so many digits of precision, so if the values you're trying to compare are greater than 999999.0, then you can't test for differences within 0.000001 of each other.