0

Need help reading float from console and maintaining decimal values. I am unable to find a good answer online. cout will print correct value but if I add a break point x reads the below given values.

Below code for input 1.45 convert x to 1.4500005 and 10.45 to 10.4499998.

#include <iostream>
using namespace std;

int main() {
    float x;    
    cin >> x;
    cout << x;
    return 0;
}
vinmen
  • 65
  • 7
  • 2
    Do you know the binary representation of 1.45? – Thomas Sablik Apr 02 '21 at 15:48
  • 2
    Maybe this is what your problem really is: [https://stackoverflow.com/questions/588004/is-floating-point-math-broken](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – drescherjm Apr 02 '21 at 15:48
  • With the edit it's definitely the duplicate. The basic idea is not all floating point numbers are representable in the hardware and the hardware uses base 2 instead of base 10 internally. – drescherjm Apr 02 '21 at 15:50

0 Answers0