在 C++ 中设置默认浮点打印精度

我想在比较期间控制双精度,然后用 C++ 恢复到默认精度.

I want to control the precision for a double during a comparison, and then come back to default precision, with C++.

我打算使用 setPrecision() 来设置精度.那么将精度设置回默认值的语法(如果有)是什么?

I intend to use setPrecision() to set precision. What is then syntax, if any, to set precision back to default?

我正在做这样的事情

std::setPrecision(math.log10(m_FTOL));

我做了一些事情,之后我想回到默认的双重比较.

I do some stuff, and I would like to come back to default double comparison right afterwards.

我是这样修改的,还是有一些错误

I modified like this, and I still have some errors

std::streamsize prec = std::ios_base::precision();
std::setprecision(cmath::log10(m_FTOL));

with cmath 在编译时为 false,而 std::ios_base 在编译时也为 false.你能帮忙吗?

with cmath false at compilation, and std::ios_base also false at compilation. Could you help?

推荐答案

你可以得到精度before你改变它,用 std::ios_base::precision 和然后使用它稍后将其更改回来.

You can get the precision before you change it, with std::ios_base::precision and then use that to change it back later.

您可以通过以下方式看到这一点:

You can see this in action with:

#include <ios>
#include <iostream>
#include <iomanip>

int main (void) {
    double d = 3.141592653589;
    std::streamsize ss = std::cout.precision();
    std::cout << "Initial precision = " << ss << '
';

    std::cout << "Value = " << d << '
';

    std::cout.precision (10);
    std::cout << "Longer value = " << d << '
';

    std::cout.precision (ss);
    std::cout << "Original value = " << d << '
';

    std::cout << "Longer and original value = "
        << std::setprecision(10) << d << ' '
        << std::setprecision(ss) << d << '
';

    std::cout << "Original value = " << d << '
';

    return 0;
}

哪个输出:

Initial precision = 6
Value = 3.14159
Longer value = 3.141592654
Original value = 3.14159
Longer and original value = 3.141592654 3.14159
Original value = 3.14159

上面的代码展示了两种设置精度的方法,第一种是调用std::cout.precision (N),第二种是使用流操作器std::setprecision(N).

The code above shows two ways of setting the precision, first by calling std::cout.precision (N) and second by using a stream manipulator std::setprecision(N).

但您需要记住,精度是针对通过流输出值的,它不会直接影响值本身与以下代码的比较:

But you need to keep in mind that the precision is for outputting values via streams, it does not directly affect comparisons of the values themselves with code like:

if (val1== val2) ...

也就是说,即使输出可能是3.14159,值本身还是完整的3.141592653590(以普通浮点数为准限制,当然).

In other words, even though the output may be 3.14159, the value itself is still the full 3.141592653590 (subject to normal floating point limitations, of course).

如果你想这样做,你需要检查它是否足够接近而不是相等,代码如下:

If you want to do that, you'll need to check if it's close enough rather than equal, with code such as:

if ((fabs (val1 - val2) < 0.0001) ...

相关文章