【问题标题】:How to align the console output to decimal point instead of left or right [duplicate]如何将控制台输出对齐到小数点而不是左或右[重复]
【发布时间】:2021-11-11 10:02:35
【问题描述】:

我正在尝试将 C++ 中的控制台输出与小数点对齐。我尝试了setwprecision 选项和其他与rightleft 对齐的标志。

但没有一个效果令人满意。

最接近的选项是使用showpos 为正数打印(+)号,但它会干扰其他格式,例如“TE_1_0”到“TE_+1_+0”

1.000000    -0.000000   0.000000
-0.000000   1.000000    0.000000
0.000000    0.000000    1.000000

如果将其与小数点对齐以将输出呈现给感兴趣的人,那就太好了。因此,我们将不胜感激。

【问题讨论】:

  • 也许显示您的代码? minimal reproducible example
  • 负值和非负值的不同格式如何?确保非负值获得额外的空间来说明为负数打印的-
  • 它是一个矩阵,所以我并没有真正按行和列中的元素打印元素。

标签: c++ console-application cout


【解决方案1】:

您可以使用setwsetfillfixedsetprecesion 的组合来执行此操作,如下所示:

#include <iostream>
#include <vector>
#include <iomanip>

int main()
{
    std::vector<std::vector<double>> vec{{10.0233, 122.1, 1203.1},{100.03, 22.15, 3.01},{107.03, 152.1, 0.1},};
    for(std::vector<double> tempVec: vec)
    {
        for(double elem: tempVec)
        {
            std::cout << std::setw(8) << std::setfill(' ') << std::fixed << std::setprecision(3) << elem << "    ";
        }
        std::cout<< std::endl;
    }
    return 0;
}

上面的输出是:

  10.023     122.100    1203.100    
 100.030      22.150       3.010    
 107.030     152.100       0.100 

如果对上面的例子稍作修改如下所示:

std::cout << std::setw(12) << std::setfill(' ') << std::fixed << std::setprecision(6) << elem << "    ";

那么输出变成:

   10.023300      122.100000     1203.100000    
  100.030000       22.150000        3.010000    
  107.030000      152.100000        0.100000 

setw 用于设置输出的最大长度,在我给定的示例中为 8 和 12。

setfill 用于用char 填充填充位置。

【讨论】:

    猜你喜欢
    • 2016-01-24
    • 1970-01-01
    • 2012-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多