In this C++ tutorial, you will learn how to find the next representable value after x in direction of y, using nextafter() function of cmath, with syntax and examples.

C++ nextafter()

C++ nextafter(x, y) next representable value after x in direction of y.

Syntax

The syntax of C++ nextafter() is

nextafter(x, y)

where

ParameterDescription
xA double, float, long double, or integral type value.
yA 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 nextafter() is

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

The synopsis of nextafter() function is

double nextafter(double x, double y);
float nextafter(float x, float y);
long double nextafter(long double x, long double y);
Promoted nextafter(Type1 x, Type2 y); // where Type1 and Type2 are any integral type values

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

ADVERTISEMENT

Example

In this example, we read two values from user, into variables x and y, and compute the next representable value next to x towards y using nextafter() function.

C++ Program

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

int main() {
    long double x, y;
    cout << "Enter x : ";
    cin >> x;
    cout << "Enter y : ";
    cin >> y;

    long double result = nextafter(x, y);
    cout << "Next Value : " << result << endl;
}

Output

Enter x : inf
Enter y : 0
Next Value : 1.79769e+308
Program ended with exit code: 0
Enter x : -inf
Enter y : 0
Next Value : -1.79769e+308
Program ended with exit code: 0
Enter x : 8555246635
Enter y : 0
Next Value : 8.55525e+09
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned the syntax of C++ nextafter(), and how to use this function to find the next representable value of a number in the direction of other number, with the help of examples.