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

C++ round() function usage and example

C++ Library Function <cmath>

C ++The round() function in returns the nearest integer value to the parameter, rounding to zero in the middle case.

round() prototype [from C ++ 11[Standard]

double round(double x);
float round(float x);
long double round(long double x);
double round(T x); // for integer types

The round() function uses a single parameter and returns a value of type double, float, or long double. This function starts with<cmath>defined in the header file.

round() parameter

The round() function uses a single parameter value for rounding.

round() return value

The round() function returns the nearest integer value to x, rounding to zero in the middle case.

Example1:round() in C ++How does it work 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;
}

When the program is executed, the output is:

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

Example2:The round() function of integer type

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

When the program is executed, the output is:

round(15) = 15

For integer values, the round function returns the same value as the input. Therefore, it is not commonly used to represent integer values in practice.

C++ Library Function <cmath>