以下代码的输出:
#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/