【016】一天一道C/C++编程题

第十六题
请编一个函数float fun(double h),函数的功能是对变量h中的值保留2位小数,并对第三位进行四舍五入(规定h中的值为正数)。
例如:若h值为8.32433,则函数返回8.32;若h值为8.32533,则函数返回8.33。

/*
请编一个函数float fun(double h),函数的功能是对变量h中的值保留2位小数,并对第三位进行四舍五入(规定h中的值为正数)。
例如:若h值为8.32433,则函数返回8.32;若h值为8.32533,则函数返回8.33。
*/

#include 
#include 
using namespace std;

#define N 3

float fun(double h)
{
    int res=0;

    res=h*pow(10,N);

    //分解出第三位小数,判断是否要四舍五入
    if((res%10)>=5)  res+=10;

    res/=10;

    return res*pow(10,-(N-1));
}

int main()
{
    double h=8.32533;

    cout<<fun(h)<<endl;

    return 0;
}

运行结果截图
【016】一天一道C/C++编程题_第1张图片

你可能感兴趣的:(C/C++)