c ++ std::stream double 值没有科学性,也没有固定的小数位数 [英] c++ std::stream double values no scientific and no fixed count of decimals

查看:35
本文介绍了c ++ std::stream double 值没有科学性,也没有固定的小数位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码将打印 a 和 b 的值:

The following code will print value of a and b:

double a = 3.0, b=1231231231233.0123456;
cout.setf(std::ios::fixed);
cout.unsetf(std::ios::scientific);
cout << a << endl << b << endl

输出为:

3.000000
1231231231233.012451

您可以看到 a 以固定的 6 位小数输出.但我想要这样的输出:

You can see that a is outputed with fixed 6 count of decimals. But I want the output like this:

3
1231231231233.012451

如何只设置一次标志,并输出上述结果.

How can i set flags only once, and output the above result.

推荐答案

浮点数的默认格式不支持请求的格式.您基本上可以使用三种设置:

The default formatting for floating point numbers won't support the formats as requested. There are basically three settings you could use:

  • std::fixed 将在小数点后使用 precision() 数字.
  • std::scientific 将使用带有 precision() 数字的科学记数法.
  • std::defaultfloat 将选择两种形式中较短的一种.
  • std::fixed which will use precision() digits after the decimal point.
  • std::scientific which will use scientific notation with precision() digits.
  • std::defaultfloat which will choose the shorter of the two forms.

(也有 std::hexfloat ,但它只是将数字格式化为机器可读的格式).

(there is also std::hexfloat but that just formats the number in an form which is conveniently machine readable).

可以做的是创建你自己的 std::num_put facet,它使用 std::fixed 将值格式化到本地缓冲区中 在发送值 1 之前格式化一个删除尾随零位.

What you could do is to create you own std::num_put<char> facet which formats the value into a local buffer using std::fixed formatting an strips off trailing zero digits before sending the values one.

这篇关于c ++ std::stream double 值没有科学性,也没有固定的小数位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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