std::setprecision设置有效数字的数量。如何使用iomanip设置精度?

我一直发现 iomanip 令人困惑和反直觉。我需要帮助。

快速互联网搜索发现(https://www.vedantu.com/maths/precision)“因此,我们将精度视为十进制数中小数点有效数字的最大数量”(重点是我的)。这也符合我的理解。但是我写了一个测试程序并且:

stm << std::setprecision(3) << 5.12345678;
std::cout << "5.12345678: " << stm.str() << std::endl;
stm.str("");

stm << std::setprecision(3) << 25.12345678;
std::cout << "25.12345678: " << stm.str() << std::endl;
stm.str("");

stm << std::setprecision(3) << 5.1;
std::cout << "5.1: " << stm.str() << std::endl;
stm.str("");

输出:

5.12345678: 5.12
25.12345678: 25.1
5.1: 5.1

如果精度为 3,则输出应为:

5.12345678: 5.123
25.12345678: 25.123
5.1: 5.1

显然,C++ 标准对与浮点数相关的“精度”的含义有不同的解释。

如果我做:

stm.setf(std::ios::fixed, std::ios::floatfield);

然后前两个值的格式正确,但最后一个值显示为5.100.

如何在没有填充的情况下设置精度?

以上是std::setprecision设置有效数字的数量。如何使用iomanip设置精度?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>