常用的两种:
- 使用setprecision操纵符
- 使用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>
头文件