c++ - 为什么 std::setprecision(6) 在固定宽度模式下流式传输超过六位数字?

标签 c++ std iostream c++03

以下代码的输出:

#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) 重置 float 标志来重新激活它。这种模式有点混合了科学和某种“没有尾随零的固定”。

关于c++ - 为什么 std::setprecision(6) 在固定宽度模式下流式传输超过六位数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22150400/

相关文章:

c++ - C++ xerces 对象的序列化导致访问冲突。

c++ - 将 boost::iostream::stream<boost::iostreams::source> 转换为 std::istream

c++ - 使用 getline(cin,n) 输入;没有打印第一个输入,我也没有使用 cin>> 在任何地方输入

c++ - 如何构造通过 std::allocator::allocate() 分配的对象?

c++ - 如何检查 std::vector 超出范围的访问

C++ 链接器错误 iostream 重载

C++11 字符串的分配要求

c++ - 静态短[9][9] getRandomBoard();

c++ - 如何在 C++ 中打乱二维数组

c++ - 创建字符串流拷贝