English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ round() 函数使用方法及示例

C++ Fonction de bibliothèque <cmath>

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

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

double round(double x);
float round(float x);
long double round(long double x);
double round(T x); // 为整型

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

round()参数

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

round()返回值

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

Exemple1:round()在C ++中如何工作?

#include <iostream>
#include <cmath>
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;
}

Lors de l'exécution du programme, la sortie est :

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

Exemple2:整数类型的round()函数

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    int x = 15;
    double result;
    result = round(x);
    cout << "round(" << x << ") = " << result << endl;
    return 0;
}

Lors de l'exécution du programme, la sortie est :

round(15) = 15

Pour les valeurs entières, l'application de la fonction round retourne la même valeur que l'entrée. Par conséquent, elle n'est pas souvent utilisée pour représenter des valeurs entières.

C++ Fonction de bibliothèque <cmath>