为什么std :: setprecision(6)流在固定宽度模式下超过六位数? [英] Why does std::setprecision(6) stream more than six digits in fixed-width mode?

查看:408
本文介绍了为什么std :: setprecision(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.123455



I expected, and wanted:


6

32.1234

6
32.1234

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

because, to the best of my knowledge, that's the extent of what a float can reliably give me on my system.

如何说服IOStreams按我想要的方式工作?

How can I persuade IOStreams to behave as I want?

推荐答案

在固定宽度模式下,作为小数位数,与科学模式相反,其中它被用作有效数字的数量。 IOStreams没有提供使用精确作为有效数字的数量而不使用科学模式的机制。

In fixed-width mode the "precision" setting is used as the number of decimal places, in contrast with scientific mode where it is used as the number of significant digits. IOStreams provides no mechanism to use "precision" as the number of significant digits without using scientific mode.

有一个第三种模式,在C ++ 11中激活 std :: defaultfloat 。如果你不设置固定或科学模式,这个默认模式是你得到的。你可以重新激活它在C ++ 03通过重置浮动标志与 s.unsetf(std :: ios_base :: floatfield)。这种模式是科学和某种固定无后缀零之间的混合。

There is a third mode, which in C++11 is activated with std::defaultfloat. This "default" mode is what you get if you don't set either fixed or scientific mode. You can re-activate it in C++03 by resetting the float flags with s.unsetf(std::ios_base::floatfield). This mode is a bit of a mix between scientific and some sort of "fixed without trailing zeros".

这篇关于为什么std :: setprecision(6)流在固定宽度模式下超过六位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆