C++ cout 对齐输出数字

标签 c++ formatting cout

#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/

相关文章:

c++ - 将对象数组写入和读取到二进制文件?

c++ - 不带参数调用的函数不会出错

c++ - 构造函数的快捷方式

C# DataRow.ToString() 在不应该时自动格式化字符串

java - 将货币格式化为区域设置特定格式

java - 如何将 LocalDate 格式化为用户位置的标准格式?

c++ - 三元表达式的类型

c++ - 如何定义operator<<方法的结束?

C++:关于使用命名空间std和cout的问题

c++ - 尝试检测基类是否具有虚拟析构函数时如何获得正确的编译器错误消息