What is the role of **std::setprecision()** without **std::fixed** in c++?
如教程http://www.cplusplus.com/reference/iomanip/setprecision/
中所示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // setprecision example #include <iostream> // std::cout, std::fixed #include <iomanip> // std::setprecision int main () { double f =3.14159; std::cout << std::setprecision(5) << f << '\ '; // prints 3.1416 and not 3.141459 why std::cout << std::setprecision(9) << f << '\ '; std::cout << std::fixed; std::cout << std::setprecision(5) << f << '\ '; std::cout << std::setprecision(9) << f << '\ '; 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,精度决定要打印多少个数字,而不是浮点后要打印的数字:
std::ios_base::precision Manages the precision (i.e. how many digits are generated) of floating
point output
这说明了四舍五入。
是的,使用
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.
精度的含义取决于是否使用固定,科学或默认格式。对于固定格式,它是小数点后的位数。对于科学来说,也是如此-但是,在该点之前总是只有一位数字;指数用于将小数点移到位置。对于默认格式,精度指定要打印的总位数(大约;这有点复杂)。
有关详细信息,请参见http://en.cppreference.com/w/cpp/io/c/fprintf,尤其是
比较:
http://www.cplusplus.com/reference/ios/defaultfloat/
http://www.cplusplus.com/reference/ios/fixed/
这是因为"当floatfield设置为固定值时,将使用定点表示法写入浮点值:该值在小数部分中的位数与精度字段(精度)所指定的位数完全相同,并且用没有指数部分。"参考http://www.cplusplus.com/reference/ios/fixed/