如何在C ++中正确打印double到cout

时间:2013-03-27 14:22:30

标签: c++ printing double cout

在发布这个问题之前我已经看了一些问题,找不到我要找的东西,所以如果它是重复的,我很抱歉。

我有这段代码:

cout << "The balance at year " << i << " will be " << char(156) << std::setprecision(2)
     << balance << endl;

据我所知,这应该打印到控制台:

£2.00
£100.46

* fyi以上只是示例我知道没有什么可以暗示这些数字,但格式应该是这样的,对吧?

但这是我的输出:

£1e+002
£1.1e+002

为什么要这样做?

据我了解,使用setprecision会显示2个小数位,仅此而已。

哦,并且也注意到几乎没有任何关于打印双打的问题,说使用setprecision实际上表明这需要包括:

#include <iomanip>

3 个答案:

答案 0 :(得分:5)

setprecision设置精度,位数。

fixed设置固定格式。

我打赌那会解决它。

答案 1 :(得分:3)

使用std::fixed设置固定格式,而不是科学记数法。

cout << "The balance at year " << i << " will be " << char(156) << std::setprecision(2) << std::fixed << balance << endl;

答案 2 :(得分:2)

这样做:

cout << "The balance at year " << i << " will be " << char(156) << std::setprecision(2) << std::fixed << balance << endl;