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

C++ lrint() function usage and example

C++ Library Function <cmath>

C ++The lrint() function in uses the current rounding mode to round the parameter to an integer value. It is similar to

C ++The lrint() function in uses the current rounding mode to round the parameter to an integer value. The current rounding mode is determined by the fesetround() function. It is similar torint()But returns long int.

lrint() prototype [from C ++ 11Standard start]

long int lrint(double x);
long int lrint(float x);
long int lrint(long double x);
long int lrint(T x); //For integer

The lrint() function takes a single parameter and returns the value long int. This function is in<cmath>Defined in the header file.

The lrint() parameter

The lrint() function takes a single parameter and rounds the value.

The lrint() return value

The lrint() function uses the rounding direction specified by fegetround() to round the parameter x to an integer value and returns the value long int.

By default, the rounding direction is set to "nearest". You can use the fesetround() function to set the rounding direction to other values.

Example1:How lrint() works in C ++work in it?

#include <iostream>
#include <cmath>
#include <cfenv>
using namespace std;
int main()
{
    //By default, the rounding direction is the nearest direction, that is, fesetround(FE_TONEAREST)
    double x = 11.87;
    long int result;
    result = lrint(x);
    cout << "Round to the nearest (" << x << ") = " << result << endl;
    
    //Intermediate values rounded up to a higher integer
    x = 11.5;
    result = lrint(x);
    cout << "Round to the nearest (" << x << ") = " << result << endl;
    //Set the rounding direction to DOWNWARD
    fesetround(FE_DOWNWARD);
    x = 11.87;
    result = lrint(x);
    cout << "Round Down (" << x << ") = " << result << endl;
    
    //Set the rounding direction to UPWARD
    fesetround(FE_UPWARD);
    x = 33.32;
    result = lrint(x);
    cout << "Round up (" << x << ") = " << result << endl;
    
    return 0;
}

When the program is run, the output is:

Round to the nearest (11.87) = 12
Round to the nearest (11.5) = 12
Round Down (11.8699) = 11
Round up (33.3201) = 34

Example2:The lrint() function for integer type

#include <iostream>
#include <cmath>
#include <cfenv>
using namespace std;
int main()
{
    int x = 15;
    long int result;
    
    //Set the rounding direction to DOWNWARD
    fesetround(FE_DOWNWARD);
    result = lrint(x);
    cout << "Round Down (" << x << ") = " << result << endl;
    return 0;
}

When the program is run, the output is:

Round Down (15) = 15

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

C++ Library Function <cmath>