Fork me on GitHub

浮点数的按精度输出

在C++中的输出的有关设置包含在头文件“iomanip”中,首先看看里面包含的一些函数:

为了实现保留小数点后N位,并以四舍五入的方式输出,需要用到setprecision和fixed。

//eg:求半径为r的圆的面积 ;输出:保留小数点后七位,四舍五入输出 
#include"iostream"
#include"iomanip"

using namespace std;
int main()
{
    const double PI=3.14159265358979323;
    int r;
    cin>>r;
    cout.setf(ios::fixed);     
    cout<<setprecision(7)<<PI*r*r;
//    cout<<fixed<<setprecision(7)<<PI*r*r;   也可以这样一行实现 
    return 0;    
}

 

posted @ 2016-02-05 13:06  Vicebery  阅读(477)  评论(0编辑  收藏  举报