为什么 std::setprecision(6) 在固定宽度模式式传输超过 6 位数字



以下代码的输出:

#include <limits>
#include <iostream>
#include <iomanip>
#include <limits>
#include <string>
#include <sstream>
using namespace std;
inline string lexical_cast(const float arg)
{
    stringstream ss;
    ss << fixed << setprecision(numeric_limits<float>::digits10) << arg;
    if (!ss)
        throw "Conversion failed";
    return ss.str();
}
int main()
{
    cout << numeric_limits<float>::digits10 << 'n';
    cout << lexical_cast(32.123456789) << 'n';
}

是:


6 32.123455

我期望并想要:


6 32.1234

因为,据我所知,这就是float在我的系统上可以可靠地提供给我的程度。

怎样才能说服IOStreams按照我的意愿行事?

在固定宽度模式下,"精度"设置用作小数位数,而科学模式则用作有效位数。IOStreams 不提供在不使用科学模式的情况下使用"精度"作为有效位数的机制。

还有第三种模式,在 C++11 中通过 std::defaultfloat 激活。这种"默认"模式是你不设置固定模式或科学模式时得到的。您可以在 C++03 中重新激活它,方法是使用 s.unsetf(std::ios_base::floatfield) 重置浮动标志。这种模式有点混合了科学和某种"固定的无尾随零"。

最新更新