【问题标题】:How can I pad a float with leading zeros when using cout << operator使用 cout << 运算符时如何用前导零填充浮点数
【发布时间】:2014-04-25 22:34:25
【问题描述】:

把这些问题放在一起:

How can I pad an int with leading zeros when using cout << operator?

Printing the correct number of decimal points with cout

我怎样才能流到std::cout,例如这个变量

double x = 7.1224

让它看起来像这样?

07.12

【问题讨论】:

  • 被否决票的奥秘...

标签: c++ cout


【解决方案1】:

结合std::setwstd::setfillstd::fixedstd::setprecision

std::cout << std::setfill('0') << std::setw(5) 
          << std::fixed << std::setprecision(2) << x;

因此,setw 的值是:2 表示所需的精度 + 2 表示所需的整数 + 1 表示浮点。

注意:x = 107.1224 将输出为107.12

【讨论】:

    猜你喜欢
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 2010-11-19
    • 2011-03-13
    • 2015-05-21
    • 2019-09-21
    相关资源
    最近更新 更多