首页 > 解决方案 > 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.

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

标签: c++iomanip

解决方案


固定格式几乎可以提供您想要的内容,只是它保留了尾随零。没有内置方法可以避免这种情况,但您可以轻松地手动删除这些零。例如,在 C++20 中,您可以使用以下命令执行以下操作std::format

std::string format_fixed(double d) {
  auto s = fmt::format("{:.3f}", d);
  auto end = s.find_last_not_of('0');
  return end != std::string::npos ? std::string(s.c_str(), end + 1) : s;
}

std::cout << "5.12345678: " << format_fixed(5.12345678) << "\n";
std::cout << "25.12345678: " << format_fixed(25.12345678) << "\n";
std::cout << "5.1: " << format_fixed(5.1) << "\n";

输出:

5.12345678: 5.123
25.12345678: 25.123
5.1: 5.1

{fmt} library的相同示例std::format基于:godbolt

免责声明:我是 {fmt} 和 C++20 的作者std::format


推荐阅读