C++保留两位小数(略微详解)

常用的两种:

  1. 使用setprecision操纵符
  2. 使用IO对象的precision成员

特别注意:

以上两种方法都是配合fixed操纵符使用。如若不使用fixed,默认会从整数部分开始计算精度,如保留2位,1.153会被打印成1.2。相反,若使用了fixed,精度会从小数部分开始计算,如1.153会被打印成1.15。

1.使用setprecision操纵符

#include <iostream>
#include <iomanip>             
using namespace std;

int main(){
	double i=1.155;

	//分开写
	cout<<setprecision(2);            
	cout<<fixed; 
	cout<<i<<endl;

	//直接合并写也可:
	cout<<setprecision(2)<<fixed<<i<<endl;
	
	return 0;
}

2. 使用IO对象的precision成员

#include <iostream>   
using namespace std;

int main(){
	double i=1.155;

	//分开写
	cout.precision(2);            
	cout<<fixed; 
	cout<<i<<endl;

	//直接合并写也可:
	cout.precision(2);    
	cout<<fixed<<i<<endl;
	
	return 0;
}

小注:

setprecision操纵符定义在<iomanip>头文件
IO对象的precision成员与fixed操纵符定义在<iostream>头文件

如需更详细的了解,建议参考《c++primer》第五版章节17.5,里面的讲解非常全面细致

猜你喜欢

转载自blog.csdn.net/weixin_44027937/article/details/129908350