打印带有设置和设置精度的浮点 - 输出不对齐



我正在尝试使用std::cout在C++中打印矩阵,但我不知道如何更正。我尝试了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;
}

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

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

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

最新更新