📜  C++ round()

📅  最后修改于: 2020-09-25 08:04:28             🧑  作者: Mango

C++中的round() 函数返回最接近参数的整数值,中间的情况舍入为零。

C++中的round() 函数返回最接近参数的整数值,中间的情况舍入为零。

round()原型[从C++ 11标准开始]

double round(double x);
float round(float x);
long double round(long double x);
double round(T x); // For integral type

round() 函数采用单个参数,并返回double,float或long double类型的值。此函数在头文件中定义。

round()参数

round() 函数采用单个参数值进行舍入。

round()返回值

round() 函数返回最接近x的整数值,中间情况从零舍入。

示例1:round()在C++中如何工作?

#include 
#include 

using namespace std;

int main()
{
    double x = 11.16, result;
    result = round(x);
    cout << "round(" << x << ") = " << result << endl;

    x = 13.87;
    result = round(x);
    cout << "round(" << x << ") = " << result << endl;
    
    x = 50.5;
    result = round(x);
    cout << "round(" << x << ") = " << result << endl;
    
    x = -11.16;
    result = round(x);
    cout << "round(" << x << ") = " << result << endl;

    x = -13.87;
    result = round(x);
    cout << "round(" << x << ") = " << result << endl;
    
    x = -50.5;
    result = round(x);
    cout << "round(" << x << ") = " << result << endl;
    
    return 0;
}

运行该程序时,输出为:

round(11.16) = 11
round(13.87) = 14
round(50.5) = 51
round(-11.16) = -11
round(-13.87) = -14
round(-50.5) = -51

示例2:整数类型的round() 函数

#include 
#include 

using namespace std;

int main()
{
    int x = 15;
    double result;
    result = round(x);
    cout << "round(" << x << ") = " << result << endl;

    return 0;
}

运行该程序时,输出为:

round(15) = 15

对于整数值,应用舍入函数将返回与输入相同的值。因此,在实践中,它通常不用于积分值。