Why does %f print large values when floating point constants are passed instead of variables?

Viewed 323

In the given program why did I get different results for each of the printfs?

#include <stdio.h>
int main()
{
    float c = 4.4e10;
    printf("%f\n", c);
    printf("%f\n", 4.4e10);
    return 0;
}

And it shows the following output:

44000002048.000000
44000000000.000000
2 Answers

A float is a type that holds a 32-bit floating point number, while the constant 4.4e10 represents a double, which holds a 64-bit floating point number (i.e. a double-precision floating point number)

When you assign 4.4e10 to c, the value 4.4e10 cannot be represented precisely (a rounding error in a parameter called the mantissa), and the closest possible value (44000002048) is stored. When it is passed to printf, it is promoted back to double, including the rounding error.

In the second case, the value is a double the whole time, without narrowing and widening, and it happens to be the case that a double can represent the value exactly.

If this is undesirable behavior, you can declare c as a double for a bit more precision (but beware that you'll still hit precision limits eventually).

You're actually printing the values of two different types here.

In the first case you're assigning a value to a variable of type float. The precision of a float is roughly 6 or 7 decimal digits, so unless the value can be represented exactly you'll see the closest value that can be represented by that type.

In the second case you're passing the constant 4.4e10 which has type double. This type has around 16 decimal digits of precision, and the value is within that range, so the exact value is printed.

Related