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

C++ lround() function usage and example

C++ Library Function <cmath>

C ++The lround() function in the middle rounds to the nearest integer value of the parameter, rounding to zero in the case of a tie. The returned value is of type long int. It is similar toround()function, but returns a long int, while round returns the same data type as the input.

lround() prototype [from C ++ 11standard [start]

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

The lround() function takes a single parameter and returns a value of type long int. This function is in<cmath>defined in the header file.

lround() parameter

The lround() function rounds a single parameter value to an integer.

lround() return value

The lround() function returns the nearest integer value to x, rounding towards zero in the case of a tie. The returned value is of type long int.

Example1:How does lround() work in C ++working?

#include <iostream>
#include <cmath>
using namespace std;
int main()
{   
    long int result;
    double x = 11.16;
    result = lround(x);
    cout << "lround(" << x << ") = " << result << endl;
    x = 13.87;
    result = lround(x);
    cout << "lround(" << x << ") = " << result << endl;
    
    x = 50.5;
    result = lround(x);
    cout << "lround(" << x << ") = " << result << endl;
    
    x = -11.16;
    result = lround(x);
    cout << "lround(" << x << ") = " << result << endl;
    x = -13.87;
    result = lround(x);
    cout << "lround(" << x << ") = " << result << endl;
    
    x = -50.5;
    result = lround(x);
    cout << "lround(" << x << ") = " << result << endl;
    
    return 0;
}

When the program is run, the output is:

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

Example2:The lround() function of integer type

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

When the program is run, the output is:

lround(15) = 15

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

C++ Library Function <cmath>