In the given program why did I get different results for each of the printf
s?
#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
printf("%f\n",0); Above line of code is undefined behavior.
The floating-point numbers serve as rough approximations of mathematical real numbers. They do not represent the exact value. For this reason, we compare the arithmetic results of float variables with a minimum tolerance value.
Floating Point Arithmetic: Issues and Limitations¶. Floating-point numbers are represented in computer hardware as base 2 (binary) fractions. has value 0/2 + 0/4 + 1/8. These two fractions have identical values, the only real difference being that the first is written in base 10 fractional notation, and the second in base 2.
The small float can not represent 1.3, 2.4, 5.6, etc. In that case, small float approximates them. It can not represent numbers bigger than 7. Besides many combinations represent the same value.
They do not represent the exact value. For this reason, we compare the arithmetic results of float variables with a minimum tolerance value. Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for the language and STL.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With