The problem I got is if I assign a large number to a float type, for example, float f = 1.0e20
then I print it to the screen with printf("f = %f\n",f)
, then on the screen it will be f = 100000002004087730000.000000
. Could anyone tell me why the number display is not 100000000000000000000.000000
. Thanks in advance.

- 585
- 1
- 9
- 21
-
2precision.......Question asked many times and in many forms on SO – Mitch Wheat Jan 19 '12 at 01:44
-
http://web.cse.msu.edu/~cse320/Documents/FloatingPoint.pdf – Daniel Kamil Kozar Jan 19 '12 at 01:46
-
See http://stackoverflow.com/questions/1839225/float-addition-promoted-to-double – Bingo Jan 19 '12 at 01:46
2 Answers
The number you are using has no exact representation in the type you are storing it. As a result, the answers will never be exactly right.
By analogy, consider a computer that used 6 decimal digits. The best you can do for 1/3
is .333333
But then 3 * (1/3) != 1
. Oh well.
And what about 2/3
? If you use .666667
then 2/3 != 2 * (1/3)
. If you use .666666
then 1/3 + 2/3 != 1
. Oh well.
That's just the way it is with floating point numbers.

- 179,497
- 17
- 214
- 278
Summarizing, floating point variables are represented as a aproximation of a fixed number which is later scaled with an exponent. In your case, the number is too big to being stored in a accurate way. Try using a double
instead and printing it out with %lf
. It'll be more accurate, although don't expect a real equality.

- 1,294
- 6
- 12
-
1
-
To print `double`s, use `%f`, the `l` modifier has no effect before an `f` conversion specifier. – Daniel Fischer Jan 19 '12 at 03:29