-1

I got some problem with c++ rounding my numbers...

My code is :

double w, semiw;
cin >> w;
semiw = w / 2.0;
cout << "w : " << w << "; semiw : " << semiw << endl;

which, when given the console input 19.9999998 returns :

w : 20; semiw : 10

and not

w : 19.9999998; semiw : 9.9999999

as one could expect. I'd like to keep the precision double is supposed to provide, which is, according to this page, 15 significant digits. How can I achieve that ? Thanks in advance for the answers :)

Community
  • 1
  • 1
Yoctoboy
  • 322
  • 3
  • 13
  • Floating point is not exact. I suggest you read [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) and [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Jesper Juhl Feb 26 '17 at 18:35
  • 4
    @JesperJuhl I don't think that's related here. – HolyBlackCat Feb 26 '17 at 18:36
  • Maybe not (although there's clearly some rounding happening). Still good reading though ;-) – Jesper Juhl Feb 26 '17 at 18:38
  • Thanks people, I couldn't find the same question here though I kind of expected it to exist. – Yoctoboy Feb 26 '17 at 18:53

1 Answers1

1

Try setting setprecision for the output:

cout << setprecision(16) << "w : " << w << "; semiw : " << semiw << endl;
AlexD
  • 32,156
  • 3
  • 71
  • 65