How to use nexttoward() in C++
The nexttowards function takes two arguments. It returns the next representable value after the first argument in the second argument’s direction.
To use the nexttowards function, include the cmath header file in the program:
#include <cmath>
Parameters
The nexttowards function takes in two parameters:
- The first parameter is the base value.
- The second parameter is the one towards which the return value is approximated.
If both the parameters have the same value, the function returns the second parameter’s value.
Return Value
The nexttowards function returns the next representable value after the first argument in the direction of the second argument.
The function can have the return value of three types:
- float
- double
- long double
These types depend on the types of arguments the programmer gives to the functions. Figure 1, below, shows the types of return types when different argument types are passed:
Example
The code belows shows how the nexttowards function works in C++:
#include <iostream>#include <cmath>#include <typeinfo>using namespace std;int main(){long double y = -1.0;double x = 0.0;cout << "nexttoward(x, y) = " << nexttoward(x, y) << endl;// the type of returned value is output d which means the returned value is of type double.cout << "The type of returned value is " << typeid(nexttoward(x, y)).name() << endl;return 0;}
Free Resources