歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++輸出精度控制

C++輸出精度控制

日期:2017/3/1 10:03:44   编辑:Linux編程

1.setprecision(n);

默認設置輸出的數字的總位數為n,包含整數和小數部分。

2.setiosflags(ios::fixed)

默認輸出6位,必須與setprecision(n)配合使用,用來控制小數位數,不夠補0

3.resetiosflags(ios::fixed);

取消精度的設置

#include <iostream>
#include <iomanip>
using namespace std;
int main () {
double f =3.14159;
cout << setprecision (5) << f << endl; //3.1416
cout << setprecision (9) << f << endl; //3.14159
cout << fixed<<setprecision (5) << f << endl; //3.14159
cout <<fixed<< setprecision (9) << f << endl; //3.141590000
10.cout<<f<<endl; //3.141590000
cout<<resetiosflags(ios::fixed)<<setprecision(9)<<f;//3.14159
return 0;
}

需注意在精度的設置是全局作用,setiosflags之後要resetiosflags還原,位數也是如此!

Copyright © Linux教程網 All Rights Reserved