数据格式控制函数:setprecision() 、fixed()和setw()函数的使用

数据格式控制函数的头文件如下所示:

#include<iomanip>

setprecision(int n) 函数

setprecision(int n)功能是控制输出流显示浮点数的有效数字位数,形参n为输出有效字符的位数,如下所示:

	cout << setprecision(3) << 0.12345 << endl;
	cout << setprecision(3) << 1.23456 << endl;

对应的输出为

0.123
1.23
请按任意键继续...

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
请按任意键继续...

如何取消fixed()函数对后续输出的影响,欢迎留言!

setw(int n)函数

控制输出的字符的宽度n,用法如下所示:

	cout << setw(2) << 10497 << endl;
	cout << setw(6) << 10497 << endl;
	cout << setw(10) << 10497 << endl;

对应的输出为:

10497
 10497
     10497
按任意键继续...

若字符的宽度不够则用空格填充。

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐