The llrint() function in C++ rounds the argument to an integral value using the current rounding mode.
The current rounding mode is determined by the function fesetround()
. It is similar to lrint(), but returns long long int instead of long int.
llrint() prototype [As of C++ 11 standard]
long long int llrint(double x); long long int llrint(float x); long long int llrint(long double x); long long int llrint(T x); // For integral type
The llrint() function takes a single argument and returns a value of type long long int. This function is defined in <cmath> header file.
llrint() Parameters
The llrint() function takes a single argument value to round.
llrint() Return value
The llrint() function rounds the argument x to an integral value, using the rounding direction specified by fegetround()
and returns the value in long long int
.
By default, the rounding direction is set to 'to-nearest'
.
The rounding direction can be set to other values using fesetround()
function.
Example 1: How llrint() works in C++?
#include <iostream>
#include <cmath>
#include <cfenv>
using namespace std;
int main()
{
// by default, rounding direction is to-nearest i.e. fesetround(FE_TONEAREST)
double x = 11.87;
long long int result;
result = llrint(x);
cout << "Rounding to-nearest (" << x << ") = " << result << endl;
// mid-way values are rounded off to higher integer
x = 11.5;
result = llrint(x);
cout << "Rounding to-nearest (" << x << ") = " << result << endl;
// setting rounding direction to DOWNWARD
fesetround(FE_DOWNWARD);
x = 11.87;
result = llrint(x);
cout << "Rounding downward (" << x << ") = " << result << endl;
// setting rounding direction to UPWARD
fesetround(FE_UPWARD);
x = 33.32;
result = llrint(x);
cout << "Rounding upward (" << x << ") = " << result << endl;
return 0;
}
When you run the program, the output will be:
Rounding to-nearest (11.87) = 12 Rounding to-nearest (11.5) = 12 Rounding downward (11.8699) = 11 Rounding upward (33.3201) = 34
Example 2: llrint() function for integral types
#include <iostream>
#include <cmath>
#include <cfenv>
using namespace std;
int main()
{
int x = 15;
long long int result;
// setting rounding direction to DOWNWARD
fesetround(FE_DOWNWARD);
result = llrint(x);
cout << "Rounding downward (" << x << ") = " << result << endl;
return 0;
}
When you run the program, the output will be:
Rounding downward (15) = 15
For integral values, applying the llrint function returns the same value as the input. So it is not commonly used for integral values in practice.