In this C++ tutorial, you will learn how to round a given number to an integral value using current rounding mode with rint() function of cmath, with syntax and examples.

C++ rint()

C++ rint() rounds given number as argument to an integral value 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++ rint() is

</>
Copy
rint(x)

where

ParameterDescription
xA double, float, long double, or integral type value.

Returns

The return value depends on the type of value passed for parameter x.

The return value of rint(x) is

  • double if x is double.
  • float if x is float.
  • long double if x is long double.

The synopsis of rint() function is

</>
Copy
double rint(double x);
float rint(float x);
long double rint(long double x);
double rint(T x); // for integral type argument values

rint() is a function of cmath library. Include cmath library in the program, if using rint() function.

Examples

1. rint() with Rounding Mode set to FE_DOWNWARD

In this example, we read a double value from user into x, and find its floor value using rint() with rounding mode set to FE_DOWNWARD.

C++ Program

</>
Copy
#include <iostream>
#include<cmath>
#include<cfenv>
using namespace std;

int main() {
    double x;
    cout << "Enter a number : ";
    cin >> x;
    
    fesetround(FE_DOWNWARD);
    
    double result = rint(x);
    cout << "rint(" << x << ") : " << result << endl;
}

Output

Enter a number : 3.8
rint(3.79999) : 3
Program ended with exit code: 0
Enter a number : -3.14
rint(-3.14001) : -4
Program ended with exit code: 0

2. rint() with Rounding Mode set to FE_TONEAREST

In this example, we read a double value from user into x, and find its floor value using rint() with rounding mode set to FE_DOWNWARD.

C++ Program

</>
Copy
#include <iostream>
#include<cmath>
#include<cfenv>
using namespace std;

int main() {
    double x;
    cout << "Enter a number : ";
    cin >> x;
    
    fesetround(FE_TONEAREST);
    double result = rint(x);
    cout << "rint(" << x << ") : " << result << endl;
}

Output

Enter a number : 3.8
rint(3.8) : 4
Program ended with exit code: 0
Enter a number : 3.12
rint(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++ rint(), and how to use this function to round given number based on current rounding mode, with the help of examples.