C++中cout输出如何控制小数点位数
setprecision(int n)函数
头文件
#include<iomanip>
控制输出流显示浮点数的有效数字位数,形参n为输出有效字符的位数
eg:
cout<<setprecision(3)<<0.123456<<endl;
cout<<setprecision(4)<<13.3456<<endl;
输出
0.123
13.35
fixed()函数
fixed()函数与setprecision(int n)并用,可以控制小数点后面有n位。
注意:setprecision()函数是控制有效数字的位数,而fixed()函数与setprecision(int n )函数结合使用是保留小数点后的位数,小数点的保留采用四舍五入,如下所示:
cout << fixed << setprecision(3) << 0.12345 << endl;
cout << fixed << setprecision(3) << 1.23456 << endl;
输出格式
0.123
1.235
在fixed()函数具有保持功能,后面都将默认为第一次设置的输出格式,如下所示:
cout << fixed <<setprecision(3) << 0.12345 << endl;
cout << 1.23456 << endl;
输出
0.123
1.235
setw(int n)函数
控制输出的字符的宽度n,用法如下所示:
cout << setw(2) << 10497 << endl;
cout << setw(6) << 10497 << endl;
cout << setw(10) << 10497 << endl;
输出
10497
10497
10497