C++ cmath nextafter() Function
Example
Get the next double value after 1.0:
double x = nextafter(1.0, 2.0);
if (x > 1.0) {
cout << "x is a little bigger than 1";
}
Definition and Usage
The nextafter() function returns the closest floating point number to x in the direction of y. If x and y are equal, it returns y.
A double cannot store every decimal number, so there is a small gap between two double values that follow each other. In the example, x is the first double after 1.0. It is so close to 1.0 that cout prints it as 1, but x > 1.0 is true.
The nextafter function is defined in the <cmath> header file.
Tip: nexttoward() does the same, but y is a long double.
Syntax
nextafter(double x, double y)
The function also works with float and long double values. Then it returns a value of the same type.
Parameter Values
| Parameter | Description |
|---|---|
| x | Required. The number to start from. |
| y | Required. The direction to go in. If y is bigger than x, the result is bigger than x. |
Technical Details
| Returns: | A double value with the closest number to x in the direction of y. |
|---|
Related Pages
Read more about math in our Math Tutorial.