In this C++ tutorial, you will learn how to round given value to long long int using llrint() function of cmath, with syntax and examples.
C++ llrint()
C++ llrint() rounds argument to long long int using current rounding mode.
The current rounding mode can be set by fesetround(), and read by fegetround(). Include cfenv library if using any of these methods.
There are four routing modes defined in cfenv.
- FE_DOWNWARD – rounding towards negative infinity
- FE_TONEAREST – rounding towards nearest representable value
- FE_TOWARDZERO – rounding towards zero
- FE_UPWARD – rounding towards positive infinity
Syntax
The syntax of C++ llrint() is
llrint(x)
where
Parameter | Description |
---|---|
x | A double, float, long double, or integral type value. |
Returns
The function returns long long int.
The synopsis of llrint() function is
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 argument values
llrint() is a function of cmath library. Include cmath library in the program, if using llrint() function.
Examples
1. lrint() with Rounding Mode set to FE_DOWNWARD
In this example, we read a double value from user into x, and find its rounded value using llrint() with rounding mode set to FE_DOWNWARD.
C++ Program
#include <iostream>
#include<cmath>
#include<cfenv>
using namespace std;
int main() {
double x;
cout << "Enter a number : ";
cin >> x;
fesetround(FE_DOWNWARD);
long long int result = llrint(x);
cout << "llrint(" << x << ") : " << result << endl;
}
Output
Enter a number : 3.8
llrint(3.79999) : 3
Program ended with exit code: 0
Enter a number : -3.14
llrint(-3.14001) : -4
Program ended with exit code: 0
2. llrint() with Rounding Mode set to FE_TONEAREST
In this example, we read a double value from user into x, and find its rounded value using llrint() with rounding mode set to FE_DOWNWARD.
C++ Program
#include <iostream>
#include<cmath>
#include<cfenv>
using namespace std;
int main() {
double x;
cout << "Enter a number : ";
cin >> x;
fesetround(FE_TONEAREST);
long long int result = llrint(x);
cout << "llrint(" << x << ") : " << result << endl;
}
Output
Enter a number : 3.8
llrint(3.8) : 4
Program ended with exit code: 0
Enter a number : 3.12
llrint(3.12) : 3
Program ended with exit code: 0
Similarly, we could check out for other rounding modes.
Conclusion
In this C++ Tutorial, we learned the syntax of C++ llrint(), and how to use this function to round given number to nearest long long int value based on current rounding mode, with the help of examples.