使用cout<<时,如何在浮点数前添加零?算子 [英] How can I pad a float with leading zeros when using cout << operator
本文介绍了使用cout<<时,如何在浮点数前添加零?算子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
将这些问题放在一起:
我如何流式传输到std :: cout,例如,此变量
How can I stream to std::cout, for example, this variable
double x = 7.1224
并使其看起来像这样吗?
And make it look like this?
07.12
推荐答案
合并 std :: setw
, std :: setfill
, std :: fixed
和 std :: setprecision
:
Combine std::setw
, std::setfill
, std::fixed
and std::setprecision
:
std::cout << std::setfill('0') << std::setw(5)
<< std::fixed << std::setprecision(2) << x;
因此,setw的值是:2表示所需的精度+ 2表示所需的整数+ 1
So, the value for setw is: 2 for the precision desired + 2 for the integer desired + 1 for the floating point.
注意: x = 107.1224
将输出为 107.12
。
这篇关于使用cout<<时,如何在浮点数前添加零?算子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文