#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