The lrint()
function takes in a number and rounds it to the nearest integral value. Then, it returns the rounded value.
To use the lrint()
function, the cmath
header file needs to be included in the program:
#include <cmath>
Rounding is completed through the use of a current rounding mode that is specified using fesetround()
.
If no mode is specified, rounding is completed using the
. Other modes are FE_DOWNWARD and FE_UPWARD. default rounding mode to-nearest
Mode | Description |
---|---|
FE_UPWARD |
The number is rounded up to the next integral. For instance, 36.3 is rounded up to 37. |
FE_DOWNWARD |
The number is rounded down to the previous integral. For instance, 32.8 is rounded down to 32. |
to-nearest |
The number is rounded to the nearest integral. For instance, 32.7 is rounded up to 33, 32.5 is rounded up to 33, and 32.3 is rounded down to 32. |
lrint() only accepts one parameter, but it can be any of the following types:
The lrint()
function always returns a value of type long int
.
The code below shows the execution of the lrint()
function using to-nearest
, FE_UPWARD
, and FE_DOWNWARD
rounding modes.
For integral values, the
lrint()
function returns the same integral value as the input.
#include <iostream>#include <cmath>#include <cfenv>using namespace std;int main() {double x= 128.8;long int answer;answer = lrint(x);// the answer is rounded to nearest integral by default.cout << x <<" rounded to nearest integral is " << answer << endl;// Values halfway from bigger and smaller integral are rounded off to the bigger one.x = 128.5;answer = lrint(x);cout << x <<" rounded to nearest integral is " << answer << endl;// setting rounding mode to DOWNWARD rounds the value to the smaller integralfesetround(FE_DOWNWARD);x = 128.74;answer = lrint(x);cout << x <<" rounded downwards is " << answer << endl;// setting rounding mode to UPWARD rounds th value to the bigger integralfesetround(FE_UPWARD);x = 33.32;answer = lrint(x);cout << x <<" rounded upwards is " << answer << endl;return 0;}
Free Resources