#include <iostream>
using namespace std;
int main()
{
cout << -0.152454345 << " " << -0.7545 << endl;
cout << 0.15243 << " " << 0.9154878774 << endl;
}
输出:
-0.152454 -0.7545
0.15243 0.915488
我希望输出看起来像这样:
-0.152454 -0.754500
0.152430 0.915488
我的解决方案:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << fixed << setprecision(6) << setw(9) << setfill(' ') << -0.152454345 << " ";
cout << fixed << setprecision(6) << setw(9) << setfill(' ') << -0.7545 << endl;
cout << fixed << setprecision(6) << setw(9) << setfill(' ') << 0.15243 << " ";
cout << fixed << setprecision(6) << setw(9) << setfill(' ') << 0.9154878774 << endl;
}
输出很好,但代码很糟糕。可以做什么? 这是我的代码 https://ideone.com/6MKd31
最佳答案
指定输出格式总是很糟糕。无论如何,您可以忽略重复在输入/输出中保留的流修饰符,并仅重复那些 transient 的 (setw
):
// change state of the stream
cout << fixed << setprecision(6) << setfill(' ');
// output data
cout << setw(9) << -0.152454345 << " ";
cout << setw(9) << -0.7545 << endl;
cout << setw(9) << 0.15243 << " ";
cout << setw(9) << 0.9154878774 << endl;
关于C++ cout 对齐输出数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49295185/