C++:cout 格式化打印

引言

介绍使用 cout 对象输出特定格式内容的方法,会随着学习不断更新。


指定整形进制

#include 
using namespace std;


int main() {

	cout << "default:\n"
		<< dec << "32: " << 32 << endl
		<< oct << "032: " << 032 << endl
		<< hex << "0x32: " << 0x32 << endl;

	cout << "\nshowbase:\n" << showbase
		<< dec << "32: " << 32 << endl
		<< oct << "032: " << 032 << endl
		<< hex << "0x32: " << 0x32 << endl;
	
	return 0;
}

C++:cout 格式化打印_第1张图片

浮点数

#include 
#include 
using namespace std;


int main() {

	// 显示小数点,默认 6 有效位
	cout << "default 1 : " << 1.0 << endl
		<< showpoint << "showpoint 1 : " << 1.0 << endl;

	// 定点数
	cout << "\nfix point:\n" << fixed
		<< 10.0 / 3.0 << endl;

	// 科学计数法
	cout << "\nfix point:\n" << scientific
		<< 10.0 / 3.0 << endl;

	// 设置显示有效位数,默认 6 位
	cout << fixed << "\ndefault: " << 10.0 / 3.0 << endl
		<< setprecision(8) << "setprecision(8): " << 10.0 / 3.0 << endl;
	
	return 0;
}

C++:cout 格式化打印_第2张图片

设置内容对齐

#include 
#include 
using namespace std;


int main() {
	
	cout << "Default set:\n" << setfill('*')
		<< setw(12) << -3.14 << endl;

	cout << "\nLeft set:\n" << left
		<< setw(12) << -3.14 << endl;

	cout << "\nInternal set:\n" << internal
		<< setw(12) << -3.14 << endl;

	cout << "\nRight set:\n" << right
		<< setw(12) << -3.14 << endl;

	return 0;
}

C++:cout 格式化打印_第3张图片

你可能感兴趣的:(C++,c++,算法,开发语言)