C++ cout 对齐输出数字

anc*_*jic 4 c++ formatting cout

#include <iostream>

using namespace std;

int main()
{
    cout << -0.152454345 << " " << -0.7545 << endl;
    cout << 0.15243 << " " << 0.9154878774 << endl;
}
Run Code Online (Sandbox Code Playgroud)

输出:

-0.152454 -0.7545
0.15243 0.915488
Run Code Online (Sandbox Code Playgroud)

我希望输出看起来像这样:

-0.152454 -0.754500
 0.152430  0.915488
Run Code Online (Sandbox Code Playgroud)

我的解决方案:

#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;
}
Run Code Online (Sandbox Code Playgroud)

输出很好,但代码很糟糕。可以做什么?这是我的代码https://ideone.com/6MKd31

Jea*_*nès 5

指定输出格式总是很糟糕。无论如何,您可以省略重复跨输入/输出守恒的流修饰符,只重复那些瞬态 ( 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;
Run Code Online (Sandbox Code Playgroud)