如教程所示http://www.cplusplus.com/reference/iomanip/setprecision/
// setprecision example
#include <iostream> // std::cout, std::fixed
#include <iomanip> // std::setprecision
int main () {
double f =3.14159;
std::cout << std::setprecision(5) << f << '\n'; // prints 3.1416 and not 3.141459 why
std::cout << std::setprecision(9) << f << '\n';
std::cout << std::fixed;
std::cout << std::setprecision(5) << f << '\n';
std::cout << std::setprecision(9) << f << '\n';
return 0;
}
std::cout << std::setprecision(5) 行不打印 5 个十进制数字,但在设置 std::fixed 后,setprecision 有效正如预期的那样。这是为什么 ?。
没有 std::fixed 的 std::setprecision() 有什么作用?
最佳答案
根据 http://en.cppreference.com/w/cpp/io/ios_base/precision ,精度决定打印多少位,而不是打印 float 后的多少位:
std::ios_base::precision
Manages the precision (i.e. how many digits are generated) of floating point output
这解释了舍入。
是的,使用 std::fixed
会改变浮点精度的解释。根据http://www.cplusplus.com/reference/ios/ios_base/precision/ :
In both the fixed and scientific notations, the precision field specifies exactly how many digits to display after the decimal point, even if this includes trailing decimal zeros. The digits before the decimal point are not relevant for the precision in this case.
关于c++ - 在 C++ 中没有 **std::fixed** 的 **std::setprecision()** 的作用是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45084317/