-2

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.

John
  • 585
  • 1
  • 9
  • 21

2 Answers2

2

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.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
0

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.

Adonais
  • 1,294
  • 6
  • 12