以下代码的输出:

#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';
}

是:



我期望并且想要:



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

我如何说服IOStreams表现自己想要的行为?

最佳答案

在固定宽度模式下,“精确”设置用作小数位数,而与科学模式相反,“精确”设置用作有效数字位数。 IOStreams没有提供任何机制来使用“精度”作为有效位数而不使用科学模式。

第三种模式在C++ 11中由std::defaultfloat激活。如果您未设置固定或科学模式,则将获得此“默认”模式。您可以在C++ 03中通过使用s.unsetf(std::ios_base::floatfield)重置float标志来重新激活它。这种模式在科学和某种“固定而不尾随零”之间有些混合。

07-24 09:46
查看更多