c++ - 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++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
。
推荐阅读
- android - 使用 MpAndroidChart 在饼图中显示大数字(双值)
- javascript - 在 JavaScript 中返回数组的值
- django - React 调用 Django API CSRF
- java - 如何从 Firebase 数据库中删除消息?
- shell - 如何把这个 Vim 命令变成一个函数?
- google-analytics - 如何在 Google Analytics 中均匀匹配事件点击和目标?
- javascript - 无法使用 IE11 动态填充下拉框
- postgresql - 跨表维护复杂的逻辑完整性
- sql - 预获取时间戳差异
- unit-testing - 如何在 .NET Core 2.1 的测试项目中加载配置数据?