在 c++ 中使用 setfill() 以特定格式打印十进制数

Print a decimal number in a particular format using setfill() in c++

本文关键字:定格 式打印 十进制数 c++ setfill      更新时间:2023-10-16

我正在尝试打印十进制编号,格式如下:"#####+3.01"情况:有一个小数点 no(在本例中假设为 3.01(。我必须打印它,前面有 y 号的符号 +/-。#,有一些固定的总宽度。(假设在这种情况下 x = 10(。

我尝试做这样的事情:

   double no = 3.01;
   cout << setfill('#') << setw(10) ;
   cout << setiosflags(ios::showpos);
   cout << fixed << setprecision(2) << no << endl;

但是我得到了以下输出:

    +#####3.01

预期输出 :

    #####+3.01

你的代码给了我正确的结果。我正在使用一台 Linux 机器。

以防万一是依赖于操作系统的问题,请尝试以下代码:

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    double no = 3.01;
    cout << setfill('#') << std::right<< setw(10) ;
    cout << setiosflags(ios::showpos);
    cout << fixed << setprecision(2) << no << endl;
}