Setprecision是令人困惑 [英] Setprecision is Confusing
问题描述
我只想问关于setprecision,因为我有点困惑。
这里是代码:
#include< iostream&
#include< iomanip>
using namespace std;
int main()
{
double rate = x;
cout<<固定< setprecision(2)<<率;
}
其中x =到以下内容:
$ b方程的左边是$的值。
1.105 = 1.10应该是1.11
1.115 = 1.11应该是1.12
1.125 = 1.12应该是1.13
1.135 = 1.14
1.145 = 1.15也正确
但如果x是:
2.115 = 2.12这是正确的
2.125 = 2.12应该是2.13
某个值是正确的,但有时却是错误的?
请启发我。感谢
没有理由期望您的帖子中的任何常量都可以 >使用浮点系统。因此,一旦将它们存储在 double
变量中(不管iostream是如何舍入这样的数字),您所拥有的精确的一半可能不再是精确的一半。 )
以下代码说明了我的观点:
#include< ; iostream>
#include< iomanip>
using namespace std;
int main()
{
double rate = 1.115;
cout<<固定< setprecision(20)<<率;
}
输出:
1.11499999999999999112
我建议您看看常见问题。
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
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.
这篇关于Setprecision是令人困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!