setprecision、fixed、showpoint的用法總結(經典!!)

轉載自https://blog.csdn.net/u011321546/article/details/9293547

首先要加頭文件:iomanip

一:setprecision

  作用:控制輸出流顯示浮點數的數字個數,setprecision(n)就是輸出的n個數,會有四捨五入。

比如:double s=20.7843000,

cout<<setprecision(1)<<s<<endl; //輸出2e+001,因爲要輸出一個數字,所以只有2.

cout<<setprecision(2)<<s<<endl; //輸出21。

cout<<setprecision(3)<<s<<endl; //輸出20.8。

cout<<setprecision(6)<<s<<endl; //輸出20.7843。

cout<<setprecision(7)<<s<<endl; //輸出20.7843。

cout<<setprecision(8)<<s<<endl; //輸出20.7843。

   可見,小數部分末尾爲0時,是輸不出來的!要想輸出來,就得用showpoint了。

特別提示

   如果再在這些語句後面加個兩個語句:

cout<<1<<endl;

cout<<1.00800<<endl;

猜到會輸出什麼嗎?

第一條輸出:1。不是浮點型。

第二條爲:1.008。承接setprecision(8)的這條規則語句。

注:

如果直接有語句

int main()

{

cout<<1<<endl;

cout<<1.00<<endl;

}

第一條輸出:1。

第二條也爲:1。按整型輸出
 

 

二:setprecision與showpoint

語法:在輸出語句前聲明:cout.setf(ios::showpoint);就行了!

還比如:double s=20.7843000,代碼如下:

cout.setf(ios::showpoint);

cout<<setprecision(1)<<s<<endl; //輸出2.e+001,注意,2和e之間多了一個“.”。

cout<<setprecision(2)<<s<<endl; //輸出21.。多個點!

cout<<setprecision(3)<<s<<endl; //輸出20.8。

cout<<setprecision(6)<<s<<endl; //輸出20.7843。

cout<<setprecision(7)<<s<<endl; //輸出20.78430。

cout<<setprecision(8)<<s<<endl; //輸出20.784300。

可見,就會輸出想要的數據數目!

 特別提示

如果再在這些語句後面加個兩個語句:

cout<<1<<endl;

cout<<1.0080<<endl;

猜到會輸出什麼嗎?

第一條輸出:1。不是浮點型。

第二條也爲:1.0080000。承接setprecision(8)的這條規則語句。

 

三:setprecision與fixed

如果想要保留幾位小數,那setprecision就得與fixed合作了!!

語法:在輸出語句前聲明:cout.setf(ios::fixed);

 比如:double s=20.7843909,代碼如下:

cout.setf(ios::fixed);

cout<<setprecision(1)<<s<<endl; //輸出2.8  。

cout<<setprecision(2)<<s<<endl; //輸出21.78。多個點!

cout<<setprecision(3)<<s<<endl; //輸出20.784。

cout<<setprecision(6)<<s<<endl; //輸出20.784391。

cout<<setprecision(7)<<s<<endl; //輸出20.7843909。

cout<<setprecision(8)<<s<<endl; //輸出20.78439090。

 特別提示

    如果也再在這些語句後面加個兩個語句:

cout<<1<<endl;

cout<<1.008<<endl;

猜到會輸出什麼嗎?

第一條輸出:1。

第二條爲:1.00800000。

就是承接了setprecision(8)的這條規則語句,是浮點型的都會保留8個小數。是整型的還是整型!)

語句也可以寫成:cout<<fixed<<setprecision(2)<<s<<endl;

       

  就算後面的語句沒有寫<<fixed,同樣會按有<<fixed處理。

比如有語句:

cout<<fixed<<setprecision(2)<<s<<endl;

A:cout<<setprecision(7)<<s<<endl;

B:cout<<setprecision(8)<<s<<endl;

AB語句均會按保留7個,8個小數處理,不會再按有7或8個浮點數處理。

 如果下面有語句c:

cout<<1.008<<endl;也會保留8個小數。

 

四:setprecision、showpoint與fixed

cout<<fixed<<setprecision(2)<<123.456<<endl; //輸出的結果是123.46
cout<<showpoint<<12345.0006666<<endl; //輸出12345.0
cout<<fixed<<setprecision(2)<<123.456<<endl;

   比如:double s=20.7843909

1.有語句

cout<<setprecision(2)<<s<<endl;//輸出21

cout<<fixed<<s<<endl;//輸出20.78

2.有語句:

cout<<setprecision(2)<<s<<endl;//輸出21

cout<<showpoint<<s<<endl;//輸出21.(有個點)

 3.有語句:

  cout<<fixed<<s<<endl;//輸出20.78391
cout<<showpoint<<s<<endl;//輸出20.78391
4.有語句:

cout<<setprecision(2)<<s<<endl;//輸出21
cout<<fixed<<s<<endl;//輸出20.78
cout<<showpoint<<s<<endl;//輸出20.78

5.有語句:

cout<<setprecision(2)<<s<<endl;//輸出21
cout<<showpoint<<s<<endl;//21.(有個點)
cout<<fixed<<s<<endl;//20.78

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章