0

I'm reading a book about C programming By "King.K.N" and I'm reading the following statement:

If we store 0.1 in a float variable, we may later find that the variable has a value such as 0.0999999999999999987

But I can't understand why float type variable may have different value?

Higgs
  • 169

1 Answers1

6

You try to store decimal 0.1 in a float variable. When we talk about float in C (and in most other languages), numbers according to IEEE Standard for Floating-Point Arithmetic (IEEE 754) are meant.

Float numbers are stored in base 2, and 1/10 cannot be converted to a binary fraction in a lossless way.

Think of how you try to store 1/3 in base 10: You end up with 0.33333. But 3 * 0.33333 is not equal to 1, but to 0.99999.

For more details, read What Every Computer Scientist Should Know About Floating-Point Arithmetic

Residuum
  • 3,332
  • 31
  • 31