使用setw和setprecision打印浮点-输出未对齐

时间:2020-08-03 22:38:21

标签: c++ vector cout

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

Matrix.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;
}

Main.cpp

    ...
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

1 个答案:

答案 0 :(得分:0)

事实证明,我只需要使用更大的参数来调用函数:

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的链接下回答更好,因为它更可定制。