C++保留小數精度
阿新 • • 發佈:2019-01-14
在C++的程式設計中,總會遇到浮點數的處理,有的時候,我們只需要保留2位小數作為輸出的結果,這時候,問題來了,怎樣才能讓cout輸出指定的小數點後保留位數呢?
在C語言的程式設計中,我們可以這樣實現它:
printf("%.2f", sample);在C++中,是沒有格式符的,我們可以通過使用setprecision()函式來實現這個需求。
想要使用setprecision()函式,必須包含標頭檔案#include <iomanip>。使用方式如下:
cout << "a=" << setprecision(2) << a <<endl;
這時候,我們會發現,如果a的值為0.20001,輸出的結果為a=0.2,後面第二位的0被省略了。如果我們想要讓它自動補0,需要在cout之前進行補0的定義。程式碼如下:
cout.setf(ios::fixed);
cout << "a=" <<fixed<< setprecision(2) << a <<endl; //輸出a=0.20
這樣,我們就可以得到0.20了。當然,如果想要關閉掉補0,只需要對fixed進行取消設定操作。cout.unsetf(ios::fixed);
cout << "a=" << setprecision(2) << a <<endl; //輸出a=0.2
我們的輸出結果就又變回a=0.2了。
參考程式碼:
轉自點選開啟連結#include <iostream> #include <iomanip> using namespace std; int main() { float a = 0.20001; cout.setf(ios::fixed); cout << "a=" <<fixed<< setprecision(2) << a <<endl; //輸出結果為a=0.20 cout.unsetf(ios::fixed); cout << "a=" << setprecision(2) << a <<endl; //輸出結果為a=0.2 return 0; }
