使用cout<<时,如何在浮点数前添加零?算子 [英] How can I pad a float with leading zeros when using cout << operator

查看:88
本文介绍了使用cout<<时,如何在浮点数前添加零?算子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将这些问题放在一起:

我如何使用使用cout<<时,前导零。

使用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&lt;&lt;时,如何在浮点数前添加零?算子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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