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

Ala*_*irG 5 c++ 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("");
Run Code Online (Sandbox Code Playgroud)

输出:

5.12345678: 5.12
25.12345678: 25.1
5.1: 5.1
Run Code Online (Sandbox Code Playgroud)

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

5.12345678: 5.123
25.12345678: 25.123
5.1: 5.1
Run Code Online (Sandbox Code Playgroud)

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

如果我做:

stm.setf(std::ios::fixed, std::ios::floatfield);
Run Code Online (Sandbox Code Playgroud)

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

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

Doc*_*h88 2

您可以尝试使用此解决方法:

decltype(std::setprecision(1)) setp(double number, int p) {
    int e = static_cast<int>(std::abs(number));
    e = e != 0? static_cast<int>(std::log10(e)) + 1 + p : p;
    while(number != 0.0 && static_cast<int>(number*=10) == 0 && e > 1) 
        e--; // for numbers like 0.001: those zeros are not treated as digits by setprecision.
    return std::setprecision(e);
}
Run Code Online (Sandbox Code Playgroud)

进而:

auto v = 5.12345678;
stm << setp(v, 3) << v;
Run Code Online (Sandbox Code Playgroud)

另一个更详细和优雅的解决方案是创建一个像这样的结构:

struct __setp {
    double number;
    bool fixed = false;
    int prec;
};

std::ostream& operator<<(std::ostream& os, const __setp& obj)
{
    if(obj.fixed)
        os << std::fixed;
    else os << std::defaultfloat;
    os.precision(obj.prec);
    os << obj.number; // comment this if you do not want to print immediately the number
    return os;
}

__setp setp(double number, int p) {
     __setp setter;
     setter.number = number;
     
    int e = static_cast<int>(std::abs(number));
    e = e != 0? static_cast<int>(std::log10(e)) + 1 + p : p;
    while(number != 0.0 && static_cast<int>(number*=10) == 0)
        e--; // for numbers like 0.001: those zeros are not treated as digits by setprecision.

    if(e <= 0) {
        setter.fixed = true;
        setter.prec = 1;
    } else
        setter.prec = e;
    return setter;
}
Run Code Online (Sandbox Code Playgroud)

像这样使用它:

auto v = 5.12345678;
stm << setp(v, 3);
Run Code Online (Sandbox Code Playgroud)