C++控制输出格式
在C++运算中有时候需要控制输出结果的精度,比如保留三位小数或者保留5位有效数字,下面简单介绍一下我用过的几种输出格式。
- 设置宽度setw(n),n即为输出固定宽度,默认以空格填充,如果加上setfill(‘0’)即以‘0’为填充,‘’内可改为其他字符。
int i = 1;
cout << setw(10) << setfill('0') << i << endl; //0000000001
cout << setw(10) << setfill('*') << i << endl; //*********1
- 设置有效位数setprecision(n),n即为设置位数
double d = 221.1161101199;
cout << d << endl; //221.116 默认六位
cout << setprecision(10) << d << endl; //221.1161101 通过设置十位
- 设置小数点后位数,先通过setiosflags(ios::fixed)设置固定小数点的位数,再通过setprecision(n),设置小数点后固定保留n位数
float f = 1.1;
double b = 221.1161101199;
cout << b << endl;
cout << setiosflags(ios::fixed) << setprecision(6) << f << endl;
cout << setiosflags(ios::fixed) << setprecision(6) << b << endl;
cout << setiosflags(ios::fixed) << setprecision(8) << f << endl;
/* 221.116 //默认六位有效数字
1.100000 //固定6位,空位自动补零
221.116110 //固定六位,后位四舍五入
221.11611012
*/
- 按进制输出,dec为十进制,hex为16进制,而也可以通过setbase(n),直接设置n进制
int a = 11111;
cout << a << endl; //11111
cout << dec << a << endl; //11111
cout << hex << a << endl; //2b67
cout << setbase(8) << a << endl; //25547
cout << setbase(16) << a << endl; //2b67