c++ - 使用 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
解决方案
原来我只需要用更大的参数调用函数:
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 的链接下回答更好,因为它更可定制。
推荐阅读
- c# - 这两个简单的 Async 和 Await 实现之间的输出差异
- .net - .NET Core 在 AzuerAD 身份验证后添加声明
- css - 尽管设置了最小宽度和高度,但溢出在网格列中不起作用
- java - Android 9:虽然有 cleartextTrafficPermitted="true",但不允许明文 HTTP 流量
- ios - UICollectionView 两个具有相同视图的单元格。第二个单元格不显示任何内容
- r - 函数中的 lme 对象使用上一次运行的响应变量
- scikit-learn - Anaconda Scikit-learn 最新版本
- excel - Workbook_BeforeClose() 在第一部分起作用,但不关闭 Workbook
- bash - 在所有子目录中递归运行命令
- deepsecurity - 更新名称存在多次的计算机对象时出现 REST API 错误