据我所知,单个 float 的精度约为 6 位,因此以下程序将输出 2
也就不足为奇了。 .
#include<iostream>
using namespace std;
int main(void) {
//cout.precision(7);
float f = 1.999998; //this number gets rounded up to the nearest hundred thousandths
cout << f << endl; //so f should equal 2
return 0;
}
但是当cout.precision(7)
包括在内,实际上在cout << f << endl;
之前的任何地方, 程序输出整个 1.999998
.这只能意味着 f
存储整个 float 而不四舍五入,对吧?
我知道cout.precision()
不应该以任何方式影响浮点存储。这种行为有解释吗?或者它只是在我的机器上?
最佳答案
I understand that single floating-point numbers have the precision of about 6 digits
大约 六位十进制数字,或恰好 23 位二进制数字。
this number gets rounded up to the nearest hundred thousand
不,它没有。它四舍五入到最接近的 23 位二进制数字。不是一回事,不能与之相提并论。
Why does
cout.precision()
increase floating-point's precision?
事实并非如此。它会影响它的打印方式。
关于c++ - 为什么 cout.precision() 会增加 float 的精度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43779599/