如下代碼:
#include<iostream>
#include<iomanip>
using namespace std;
void main()
{
double f = 3.1415926535;
cout << "Enter the huashi temperature:" << endl;
//-----------------方法一-------------------
/* cout.precision(3); //調用cout的precision()函數設置或返回當前要被顯示的浮點變量的位數(即浮點數的數字個數)
cout << fixed; //fixed輸出小數點後面三位有效數字
cout << "The Celsius temperature is: ";
cout << f << endl; //輸出小數點前後共三位有效數字
cout << f << endl;
*/
//----------------方法二--------------------
//使用setprecision()操作符,包含在在iomanip頭文件中
cout << f << endl; //默認輸出六位
cout << setprecision(3); //單用setprecision是設置顯示的有效數字位數。
cout << setprecision(0) << f << endl;
cout << setprecision(1) << f << endl;
cout << setprecision(2) << f << endl;
cout << setprecision(3) << f << endl;
cout << setprecision(4) << f << endl;
cout << "---------------------------------" << endl;
cout <<setiosflags(ios::fixed); //配合setprecision就是設置小數精度(小數點後的有效位數)
//cout << fixed; //作爲cout的一個參數是setiosflags(ios::fixed)的簡寫形式,等效於上一行
cout << setprecision(0) << f << endl;
cout << setprecision(1) << f << endl;
cout << setprecision(2) << f << endl;
cout << setprecision(3) << f << endl;
cout << setprecision(4) << f << endl;
}