C++格式化输出相关

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
	cout << "格式化进制" << endl;
	long num = 1001;
	// 不同进制输出, 不支持二进制;八进制和十六进制目前仅支持正整数
	cout << "dec: " << std::dec << num << endl
		<< "hex: " << std::hex << num << endl
		<< "oct: " << std::oct << num << endl;
	
	num = -1001;
	cout << "dec: " << std::dec << num << endl
		<< "hex: " << std::hex << num << endl
		<< "oct: " << std::oct << num << endl;
	
	std::dec(cout);

	//设置宽
	cout << endl << "格式化位宽" << endl;
	cout << setw(4) << 1 <<endl
		<< setw(4) << 10 << endl
		<< setw(4) << 100 << endl
		<< setw(4) << 1000 << endl
		<< setw(4) << 10000 << endl
		<< setw(4) << 100000 << endl;

	cout << setw(-4) << 1 << endl
		<< setw(-4) << 10 << endl
		<< setw(-4) << 100 << endl
		<< setw(-4) << 1000 << endl
		<< setw(-4) << 10000 << endl
		<< setw(-4) << 100000 << endl;

	for (int j = 0; j < 5; ++j) {
		for (int i = 0; i < 5; ++i) {
			cout << setw(4) << i * i * i *i;
		}
		cout << endl;
	}

	for (int j = 0; j < 5; ++j) {
		for (int i = 0; i < 5; ++i) { //对齐
			cout << setw(-24) << i * i * i *i;
		}
		cout << endl;
	}

	cout <<endl<< "格式化精度" << endl;

	double dou_val = -12.85555555;
	cout << "负数精度:" << endl;
	cout << dou_val << endl;		// 默认总的精度6位 (符号不算)                
	cout << setprecision(3) << dou_val << endl;  //四舍五入,总的精度3位
	cout << setprecision(4) << dou_val << endl;  //四舍五入,总的精度4位

	cout << endl << "正数精度:" << endl;
	dou_val = 12.718281828;
	cout << setprecision(6)<<dou_val << endl;     // 默认总的精度6位                 
	cout << setprecision(3) << dou_val << endl;  //四舍五入,总的精度3位
	cout << setprecision(4) << dou_val << endl;  //四舍五入,总的精度4位
	cout << fixed << setprecision(5) << dou_val << endl;	//小数位为5位
	cout << dou_val << endl;
	cout.unsetf(ios::fixed);
	cout << dou_val << endl;  //恢复总精度5位

	getchar();
	return 0;
}

结果:

格式化进制
dec: 1001
hex: 3e9
oct: 1751
dec: -1001
hex: fffffc17
oct: 37777776027

格式化位宽
   1
  10
 100
1000
10000
100000
1
10
100
1000
10000
100000
   0   1  16  81 256
   0   1  16  81 256
   0   1  16  81 256
   0   1  16  81 256
   0   1  16  81 256
011681256
011681256
011681256
011681256
011681256

格式化精度
负数精度:
-12.8556
-12.9
-12.86

正数精度:
12.7183
12.7
12.72
12.71828
12.71828
12.718

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值