cout 输出小数点后指定位数

cout 输出小数点后指定位数

C++ 控制cout输出的小数位数

C++——cout输出小数点后指定位数

在C++中,是没有格式符的,我们可以通过使用setprecision()函数来实现这个需求

想要使用 setprecision() 函数,必须包含头文件#include <iomanip>,使用方式如下

cout << "a=" << setprecision(2) << a <<endl;

如果 a 的值为 0.20001,输出的结果为 a = 0.2,后面第二位的 0 被省略

如果想要自动补0,需要在cout之前进行补0的定义,代码如下

cout.setf(ios::fixed);
cout << "a=" <<fixed<< setprecision(2) << a <<endl; //输出a=0.20

也可以在输出前对 cout 进行设置,代码如下

cout.setf(ios::fixed);
cout.precision(3);
cout << a << endl;

测试代码如下

#include <iostream>
#include <iomanip> 
using namespace std;
int main()
{
    
    
	cout << "test 1 =======" << endl;
	double f = 3.1415926535;
	cout << f << endl; // 3.14159
	cout << setiosflags(ios::fixed); //只有在这项设置后,setprecision才是设置小数的位数。
	cout << setprecision(0) << f << endl; //输出0位小数,3
	cout << setprecision(1) << f << endl; //输出1位小数,3.1
	cout << setprecision(2) << f << endl; //输出2位小数,3.14
	cout << setprecision(3) << f << endl; //输出3位小数,3.142
	cout << setprecision(4) << f << endl; //输出4位小数,3.1416
 
	cout << "test 2 =======" << endl;
	//cout.setf跟setiosflags一样,cout.precision跟setprecision一样
	float a = 0.546732333;
	float b = 3.563768245;
	cout << a << endl;
	cout << b << endl;
	cout.setf(ios::fixed);
	cout.precision(3);
	cout << a << endl;
	cout << b << endl;
	cout.precision(1);
	cout << a << endl;
	cout << b << endl;
	return 0;
}

运行输出

test 1 =======
3.14159
3
3.1
3.14
3.142
3.1416
test 2 =======
0.5467
3.5638
0.547
3.564
0.5
3.6

如果想要关闭掉补 0,只需要对fixed进行取消设置操作,代码如下

cout.unsetf(ios::fixed);
cout << "a=" << setprecision(2) << a <<endl; //输出a=0.2

猜你喜欢

转载自blog.csdn.net/Solititude/article/details/131699696