C++格式化输出

下面介绍几种常用的C++格式化输出情况

——注:要加上一个头文件
#include

1. 输出保留几位小数

#include 
#include 
using namespace std;

int main()
{
     
	double x = 112.3456789;
	cout << std::fixed << std::setprecision(2) << x << endl;
	cout << std::fixed << std::setprecision(10) << x << endl;
	return 0;
}

输出为:

112.35
112.3456789000

2. 输出保留几位数,以及用哪种字符填充,左对齐及右对齐

#include 
#include 
using namespace std;

int main()
{
     
	int x = 1234;
	cout << setw(6) << setfill('0') << x << endl;//单引号内的“0”可以用其它字符代替; 默认为右对齐
	cout << setiosflags(ios::left) << setw(6) << setfill('0') << x << endl;//此处为左对齐的输出方式
	return 0;
}

输出为:

001234
123400

这篇文章就到这啦,如果有什么问题,欢迎交流!

你可能感兴趣的:(C++小碎碎念,c++)