C++输出精度(precision)控制,格式化输出
使用cout对象的成员
- setprecision()
 
- setf()
 
- width()
 
- fill()
 
- flags(ios::fixed)
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
   | #include<iostream> using namespace std;
  int main() { 	double a=3.1415926; 	double c=66.666666;
  	cout.precision(3);         	cout<<a<<endl; 	cout<<c<<endl;
  	cout<<endl;
  	cout.width(8);            	cout.setf(ios::right);    	cout<<a<<endl;
  	cout<<endl;
  	cout.setf(ios::right); 	cout.fill('#');           	cout.width(8); 	cout<<a<<endl;
  	cout<<endl;
  	cout.flags(ios::fixed);  	cout.precision(4); 	cout<<a<<endl;
  	return 0; }
   | 
 

使用头文件iomanip中的setprecision()和setiosflags(ios::fixed)进行精度控制
1 2 3 4 5 6 7 8 9 10 11 12 13 14
   | #include<iostream> #include<iomanip> using namespace std;
  int main() { 	double e = 2.7182818;
  	cout<<setprecision(3)<<e<<endl;
  	cout<<setiosflags(ios::fixed)<<endl;     cout<<setprecision(3)<<e<<endl;     return 0; }
   | 
 

参考自:
https://blog.csdn.net/yanglingwell/article/details/49507463