0
    float a = 20000115;
    cout << a;

in debug , variable window is 20000116. why? how to fix this bug?

enter image description here like this image

魏达强
  • 1
  • 2
  • 5
    That number requires 25 bits to represent exactly. A float has 23 bits available to represent an exact value. It's not a bug, it is simply the way floating point values work. Not all numbers can be exactly represented. [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) for the long explanation. – Retired Ninja Dec 25 '22 at 06:28
  • 1
    @RetiredNinja: Although you are probably correct in this case (and using `double` would "solve" this specific problem), the size of a `float` is C++ is at the discretion of the particular compiler. – Scott Hunter Dec 25 '22 at 06:31

1 Answers1

3

This is called precision loss. It's not a bug. Use double instead of float, it will solve the issue.

pr0to
  • 246
  • 2
  • 9