The rint() 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().
rint() prototype [As of C++ 11 standard]
double rint(double x); float rint(float x); long double rint(long double x); double rint(T x); // For integral type
The rint() function takes a single argument and returns a value of type double, float or long double type. This function is defined in <cmath> header file.
rint() Parameters
The rint() function takes a single argument value to round.
rint() Return value
The rint() function rounds the argument x to an integral value, using the rounding direction specified by fegetround() and returns the value. 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 rint() 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, result;
result = rint(x);
cout << "Rounding to-nearest (" << x << ") = " << result << endl;
// upper value is taken for mid-way values
x = 11.5;
result = rint(x);
cout << "Rounding to-nearest (" << x << ") = " << result << endl;
// setting rounding direction to DOWNWARD
fesetround(FE_DOWNWARD);
x = 11.87;
result = rint(x);
cout << "Rounding downward (" << x << ") = " << result << endl;
// setting rounding direction to UPWARD
fesetround(FE_UPWARD);
x = 33.32;
result = rint(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: rint() function for integral types
#include <iostream>
#include <cmath>
#include <cfenv>
using namespace std;
int main()
{
int x = 15;
double result;
// setting rounding direction to DOWNWARD
fesetround(FE_DOWNWARD);
result = rint(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 rint function returns the same value as the input. So it is not commonly used for integral values in practice.