Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

c++ - Setprecision is Confusing

I just want to ask about setprecision because I'm a bit confused.

here's the code:

#include <iostream>
#include <iomanip>
using namespace std;

int main()

{
  double rate = x;
  cout << fixed << setprecision(2) << rate;
}

where x = to following:

the left side of equation are the values of x.

1.105 = 1.10 should be 1.11

1.115 = 1.11 should be 1.12

1.125 = 1.12 should be 1.13

1.135 = 1.14 which is correct

1.145 = 1.15 also correct

but if x is:

2.115 = 2.12 which is correct

2.125 = 2.12 should be 2.13

so why in a certain value it's correct but sometimes it's wrong?

please enlighten me. thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is no reason to expect that any of the constants in your post can be represented exactly using the floating-point system. As a consequence, the exact halves that you have may no longer be exact halves once you store them in a double variable (regardless of how the iostreams are meant to round such numbers.)

The following code illustrates my point:

#include <iostream>
#include <iomanip>

using namespace std;

int main()

{
  double rate = 1.115;
  cout << fixed << setprecision(20) << rate;
}

Output:

1.11499999999999999112

I would recommend taking a look at the FAQ.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...