int main(){
    float f1=14.375;
    float f2=14.385;
    return 0;

the output of this prog is


but i had expected


plz explain me the output...??

3 Years
Discussion Span
Last Post by nullptr

Basically a floating point number is an approximation and if nothing else is specified then floating point constants have the type double.

This means that in the line float f2=14.385; the compile converted the double constant 14.385 to a float and then assigned it to f2; then in if(f2==14.385), since the compiler always converts to the largest type present for comparisons it converted the floating point value of f2 to a double, in the process of all that converting the compiler took an approximation that was not quite equal to the original 14.385 so the == returned false.

On my system it happened on float f2=14.385;

f2 ended with a value of 14.38500023 when converted back to a double.


Banfa is quite correct about floating point representations. Trying to get an exact comparison of floats is not simple due to the inability to exactly represent a fractional number like you are trying to do. Integer values are a lot more precise in computer terms since they can be perfectly represented as a set of bits.

In your case, if you used doubles instead of floats, and cast the decimal values accordingly, you might get away with it... :-) Caveat Programmer!


If you wanted cast iron assurance go for a bignum library like gmp. Which actually handles integers and floating point numbers as strings.

This would ensure cross platform assurance but obviously you negate the benefits of using 64bit OS and the computations are slower.


Basically the issue has to do with precision, and how the compiler compares floats and doubles.
If you want to compare two doubles, then you have to provide a certain tolerance.
For example, the following code snippet compares f1 with 14.375 with a tolerance of 0.001:

if (fabs(f1 - 14.375) < 0.001)
//do something here

This should also be used when implementing the "equal or less than" or "equal or greater than" operators.


Lucky (or unlucky depending on your point of view) happenstance that 14.375 is exactly representable as both a float and a double. Don't rely on this.

Edited by Banfa


so u mean it depends on memory representation of float and double and the how the conversion is done at memory level... i know the representation of float and double in memory but i dont know how conversion of float to double is done at memory level. plz explain that.. i want to knw how 14.375 float is same as 14.375 double in memory but no so for 14.385.


i want to knw how 14.375 float is same as 14.375 double in memory but no so for 14.385.

Likely because 14.375 is exactly 14 3/8 which would fit the floating point model used.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.