取近似值

来源:互联网 发布:如何引出大数据 编辑:程序博客网 时间:2024/05/22 15:33

题目

描述

写出一个程序,接受一个浮点数值,输出该数值的近似整数值。如果小数点后数值大于等于5,向上取整;小于5,则向下取整。

输入

输入一个浮点数值

输出

输出该数值的近似整数值

样例输入

5.5

样例输出

6

思路1

利用函数round直接来求。

代码1

#include <iostream>#include <math.h>using namespace std;int main(){    double input;    cin>>input;    cout<<round(input);    return 0;}

思路2

自己实现round函数

代码2

#include <iostream>#include <math.h>using namespace std;int main(){    double input=0.0;    int integer=0;    int delta=0;    cin>>input;    integer = input;    if(input>0)    {        if((input-integer)>=0.5)        {            cout<<integer+1<<endl;        }        else        {            cout<<integer<<endl;        }    }    else    {        if((integer-input)>=0.5)//负数需要倒着减        {            cout<<integer-1<<endl;        }        else        {            cout<<integer<<endl;        }    }    return 0;}
0 0