gpt4 book ai didi

c++ - 仅使用标准 C++ 将任何 float 打印到恰好 N 个空格

转载 作者:太空狗 更新时间:2023-10-29 20:17:52 25 4
gpt4 key购买 nike

我有一个 float ,我想精确地打印到 N 个空格。例如,N = 5。我想打印以下数字:

0.1        => 0.1
123.456789 => 123.5
-123.45678 => -123 (or -123.)
0.123456 => 0.123
123456.789 => 123456 (obviously, in this case, we cannot print less than 6 digits, if I can detect this, I can also print 12** to indicate the field is too wide.

我尝试了很多组合,包括以下:

// Leave 3 extra space: One for negative sign, one for zero, one for decimal
std::cout << std::setiosflags(std::ios::fixed)
<< std::setprecision(N - 3)
<< std::setw(N)
<< input;

但结果并不理想。也许我遗漏了一些明显的东西?

这些示例输入的给定代码的输出是

 0.10     // not bad 
123.46 // Use 6 instead of 5 spaces
-123.46 // Use 7 instead of 5 spaces
0.12 // Under-use the spaces
123456.79 // Ok, I guess

最佳答案

为此使用 Boost 的 Spirit.Karma:

#include <boost/spirit/include/karma.hpp>
namespace karma = boost::spirit::karma;

double d = 12345.6;

// will print: 12345
std::cout << karma::format(
karma::maxwidth(5)[karma::double_], d
) << std::endl;

这将在任何情况下将输出的宽度限制为 5。如果您想捕捉数字被截断的情况(如您的 123456.7 示例),只需预先执行适当的检查:

if (d < 1e6) {
// d == 12345 will print: 12345
std::cout << karma::format(
karma::maxwidth(5)[karma::double_], d
) << std::endl;
}
else {
// d == 123456 will print: 12***
std::cout << karma::format(
karma::left_align(5, '*')[
karma::maxwidth(2)[karma::double_]
], d
) << std::endl;
}

是的,如果您可能会问,Boost 的 Spirit.Karma 是仅使用标准 C++ 功能编写的。

关于c++ - 仅使用标准 C++ 将任何 float 打印到恰好 N 个空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5711915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com