今天很驚奇,發現了C++的格式化輸出可以四捨五入地保留小數
首先我們設置cout.setf(ios::fixed);
setf是setflag的縮寫,MSDN解釋爲Sets the specificed flags。呵呵,估計是和C++的封裝有關吧。
然後我們設置cout.prevision(2);這個是保留兩位小數,四捨五入
我們可以用以下這個程序進行測試
#include<iostream>
using namespace std;
int main()
{
float a=3.1456;
cout.setf(ios::fixed);
cout.precision(2);
cout<<a<<endl;
return 0;
}