在C ++中格式化输出 [英] Formatting output in C++

查看:151
本文介绍了在C ++中格式化输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++代码中,我有一个双变量矩阵,我打印出来。然而,因为它们都具有不同数目的数字,所以输出格式被破坏。一个解决方案是做
cout.precision(5)但我想要不同的列有不同的精度。此外,因为在某些情况下有负值,所以 - 符号的存在也会导致问题。

In a C++ code I have a matrix of double variables which I print out. However because all of them have different number of digits, the output format is destroyed. One solution is to do cout.precision(5) but I want different columns have a different precision. Also, because there are negative values in some cases, the presence of the - sign also causes problems. How to get around this and produce a properly formatted output?

推荐答案

关于我的头,你可以使用setw )来指定输出的宽度。

Off the top of my head, you can use setw(int) to specify the width of the output.

像这样:

std::cout << std::setw(5) << 0.2 << std::setw(10) << 123456 << std::endl;
std::cout << std::setw(5) << 0.12 << std::setw(10) << 123456789 << std::endl;

提供:

    0.2    123456
   0.12 123456789

这篇关于在C ++中格式化输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆