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

Utilizzo e esempio della funzione round() in C++

函数库cmath

La funzione round() in C++ restituisce il valore intero più vicino al parametro, arrotondando a zero nei casi intermedi.

Procedura round() [dalla norma C++ 11]

double round(double x);
float round(float x);
long double round(long double x);
double round(T x); // Per interi

La funzione round() utilizza un singolo parametro e restituisce un valore di tipo double, float o long double. Questa funzione è disponibile a partire dalla<cmath>Definito nel file di intestazione.

Parametro di round()

La funzione round() utilizza un singolo valore di parametro per l'arrotondamento.

Valore di ritorno di round()

La funzione round() restituisce il valore intero più vicino a x, arrotondando a zero nei casi intermedi.

Esempio 1: Come funziona round() in 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;
}

运行该程序时,输出为:

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

Esempio 2: La funzione round() di tipo intero

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

运行该程序时,输出为:

round(15) = 15

对于整数值,应用round函数将返回与输入相同的值。所以它在实际中并不常用来表示整数值。

函数库cmath