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

C nexttoward

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

Syntax

The syntax of C++ nexttoward() is

nexttoward(x, y)

where

Parameter Description
x A double, float, long double, or integral type value.
y A 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 nexttoward() is

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

The synopsis of nexttoward() function is

double nexttoward(double x, long double y);
float nexttoward(float x, long float y);
long double nexttoward(long double x, long double y);
double nexttoward(T x, long double y); // where T is any integral type

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

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 nexttoward() 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 = nexttoward(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++ nexttoward(), 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.