c語言中,用print可以有格式符號,例如想讓a保留兩位小數
float a; print( "%.2f", a);
注意這里如果a是0.1, 那么打印出來會自動補0,也就是結果顯示為0.10。
c++中沒有這種格式符,所以用std中函數設定。(iomanip庫)
一種寫法是提前聲明,一種是cout << xxx << endl中聲明
#include <iostream> #include <iomanip> using namespace std; int main() { float a = 0.123; cout << a << " without setting" << endl; cout << setprecision(5) <<a << " without fixed" << endl; cout.setf( ios::fixed ); cout << setprecision(5) << a << " with fixed" << endl; cout.setf(ios::fixed); cout.precision(5); cout << a << " with fixed" << endl; }
輸出結果為
0.123 without setting
0.123 without fixed
0.12300 with fixed
0.12300 with fixed
setprecision()控制輸出流,所以要寫在cout << xxxxxxxxxxxxx <<endl中,
cout.precision可以提前控制輸出精度,
兩種方法都可以設置精度大小
fixed是設置補零,如果不想補零,可以關閉fixed設定
cout.unsetf(ios::fixed);
PS:設置精度是會四舍五入的,比如0.987,設置精度為2,則會進一位 輸出0.99