round()函数以及C ++中的示例

C ++round()函数

round()函数cmath标头的库函数,用于对最接近该数字的给定值进行舍入,将中途情况舍入为零,然后接受一个数字并返回舍入后的值。

round()函数语法:

    round(x);

参数: x –是中途取整的数字,最接近零。

返回值: double-返回double类型值,该值是数字x的舍入值。

示例

    Input:
    float x = 2.3;    
    Function call:
    round(x);    
    Output:
    2

    Input:
    float x = 2.8;
    Function call:
    round(x);    
    Output:
    3

C ++代码演示round()函数示例

//示例 
// round()功能

#include <iostream>
#include <cmath>
using namespace std;

// main()部分
int main(){
    float x;
    
    x = 15.3;
    cout<<"round("<<x<<"): "<<round(x)<<endl;

    x = 15.5;
    cout<<"round("<<x<<"): "<<round(x)<<endl;

    x = 15.8;
    cout<<"round("<<x<<"): "<<round(x)<<endl;

    x = -15.3;
    cout<<"round("<<x<<"): "<<round(x)<<endl;

    x = -15.5;
    cout<<"round("<<x<<"): "<<round(x)<<endl;

    x = -15.8;
    cout<<"round("<<x<<"): "<<round(x)<<endl;    

    return 0;
}

输出结果

round(15.3): 15
round(15.5): 16
round(15.8): 16
round(-15.3): -15
round(-15.5): -16
round(-15.8): -16