首页 > 解决方案 > 使用 setw 和 setprecision 打印浮点数 - 输出不对齐

问题描述

我正在尝试使用 C++ 打印矩阵std::cout,但我不知道如何正确执行此操作。我尝试了 和 之类的变体setw()setprecision()但仍未达到所需的外观(您可以在此问题的底部看到它)。

矩阵.cpp

template<class T>
class Matrix
{
public:

    ...

    void print(int precision=5);

    ...

private:
    size_t rows;
    size_t cols;
    std::vector<T> data;
};

template<class T>
void Matrix<T>::print(int precision)
{
    for (int i = 0; i < (int)this->rows; i++) {
        for (int j = 0; j < (int)this->cols; j++) {
            //cout << ... << " ";
        }
        cout << endl;
    }
    cout << endl;
}

主文件

    ...
int main()
{
    ...
    matrix.print(4);
    ...
}

一些尝试:

cout << data.at(i*cols + j) << " ";
Output:
-21.4269 -11.9088 -14.8804 -11.1715 3.77597
16.1763 10.68 7.99879 -0.849034 -11.9758
15.7518 -19.1033 6.27838 -3.86534 21.4716
cout << fixed << data.at(i*cols + j) << " ";
Output:
-21.426937 -11.908819 -14.880438 -11.171500 3.775967
16.176332 10.679954 7.998794 -0.849034 -11.975848
15.751815 -19.103265 6.278383 -3.865339 21.471623

在这里我尝试使用 setprecision()

cout << setprecision(precision) << data.at(i*cols + j) << " ";
Output:
-21.43 -11.91 -14.88 -11.17 3.776
16.18 10.68 7.999 -0.849 -11.98
15.75 -19.1 6.278 -3.865 21.47
cout << setprecision(precision) << fixed << data.at(i*cols + j) << " ";
Output:
-21.4269 -11.9088 -14.8804 -11.1715 3.7760
16.1763 10.6800 7.9988 -0.8490 -11.9758
15.7518 -19.1033 6.2784 -3.8653 21.4716

在这里我使用 setw()

cout << setw(precision) << data.at(i*cols + j) << " ";
Output:
-21.4269 -11.9088 -14.8804 -11.1715 3.77597
16.1763 10.68 7.99879 -0.849034 -11.9758
15.7518 -19.1033 6.27838 -3.86534 21.4716
cout << setw(precision) << fixed << data.at(i*cols + j) << " ";
Output:
-21.426937 -11.908819 -14.880438 -11.171500 3.775967
16.176332 10.679954 7.998794 -0.849034 -11.975848
15.751815 -19.103265 6.278383 -3.865339 21.471623

我真正需要的是:

-21.42 -11.91 -14.88 -11.17 3.7760
16.176 10.680 7.9988 -0.849 -11.98
15.752 -19.10 6.2784 -3.865 21.472

标签: c++vectorcout

解决方案


原来我只需要用更大的参数调用函数:

cout << setw(10) << fixed << data.at(i*cols + j) << " ";
Output:
-21.426937 -11.908819 -14.880438 -11.171500   3.775967
 16.176332  10.679954   7.998794  -0.849034 -11.975848
 15.751815 -19.103265   6.278383  -3.865339  21.471623

是的,在提供@Andy 的链接下回答更好,因为它更可定制。


推荐阅读