lrint() Function
The lrint() function rounds a floating-point value to the nearest integral value, following the current rounding mode, and then casts the result to a long integer. It is particularly useful when you need to convert a floating-point number into a long integer with proper rounding behavior.
Syntax of lrint()
</>
                        Copy
                        long int lrint(double x);Parameters
| Parameter | Description | 
|---|---|
| x | The floating-point value to be rounded. | 
Note: The function rounds the value according to the current rounding mode, as set by fegetround(). If the rounded result exceeds the range representable by a long int, a domain or overflow error may occur depending on the implementation.
Examples for lrint()
Example 1: Basic Rounding of a Positive Floating-Point Number
Program
</>
                        Copy
                        #include <stdio.h>
#include <math.h>
int main() {
    double value = 3.7;
    long int result = lrint(value);
    printf("Rounded result: %ld\n", result);
    return 0;
}
Explanation:
- A positive floating-point number 3.7is assigned to the variablevalue.
- The lrint()function rounds3.7to the nearest integer based on the current rounding mode.
- The rounded value is stored in the variable resultand then printed.
Program Output:
Rounded result: 4Example 2: Basic Rounding of a Negative Floating-Point Number
Program
</>
                        Copy
                        #include <stdio.h>
#include <math.h>
int main() {
    double value = -2.3;
    long int result = lrint(value);
    printf("Rounded result: %ld\n", result);
    return 0;
}
Explanation:
- A negative floating-point number -2.3is stored invalue.
- The lrint()function rounds the number to the nearest integral value considering the current rounding mode.
- The resulting long integer is stored in resultand printed.
Program Output:
Rounded result: -2Example 3: Rounding a Value Exactly at the Midpoint
Program
</>
                        Copy
                        #include <stdio.h>
#include <math.h>
int main() {
    double value = 2.5;
    long int result = lrint(value);
    printf("Rounded result: %ld\n", result);
    return 0;
}
Explanation:
- The midpoint value 2.5is assigned tovalue.
- lrint()rounds- 2.5based on the current rounding mode.
- The resulting long integer is saved in resultand printed.
Program Output:
Rounded result: 2Example 4: Rounding a Large Floating-Point Number
Program
</>
                        Copy
                        #include <stdio.h>
#include <math.h>
int main() {
    double value = 12345678.9;
    long int result = lrint(value);
    printf("Rounded result: %ld\n", result);
    return 0;
}
Explanation:
- A large floating-point value 12345678.9is stored invalue.
- lrint()rounds the value to the nearest integral value, taking the current rounding mode into account.
- The result is cast to a long integer, stored in result, and then printed.
Program Output:
Rounded result: 12345679