C++ nearbyint()

C++ nearbyint(x) rounds argument x to nearest integral value, using current rounding mode.

The current rounding mode can be accessed using fesetround() and fegetround().

Syntax

The syntax of C++ nearbyint() is

nearbyint(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 nearbyint(x) is

  • double if x is double or integral type.
  • float if x is float.
  • long double if x is long double.

The synopsis of nearbyint() function is

double sinh(double x);
float sinh(float x);
long double sinh(long double x);
double sinh(T x); // for integral type argument values

nearbyint() is a function of cmath library. Include cmath library at the start of program, if using nearbyint() function.

Example

In this example, we read a value from user into variable x, and find the nearest integral value of x using nearbyint() function.

C++ Program

#include <iostream>
#include<cmath>
using namespace std;

int main() {
    double x;
    cout << "Enter x   : ";
    cin >> x;
    
    double result = nearbyint(x);
    cout << "nearbyint(" << x << ") : " << result << endl;
}

Output

Enter x   : 5.23
nearbyint(5.23) : 5
Program ended with exit code: 0
Enter x   : 9.89
nearbyint(9.89) : 10
Program ended with exit code: 0
Enter x   : nan
nearbyint(nan) : nan
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned the syntax of C++ nearbyint(), and how to use this function to find the nearest integral value, with the help of examples.