English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ nextafter() function usage and example

C++ Library Function <cmath>

C ++uses two parameters in nextafter(x, y) and returns the next representable value after x in the direction of y.

The function in<cmath>Defined in the header file.

nextafter() prototype[From C ++ 11Standard starting]

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); // Additional overloads

From C ++ 11Starting from C, if the parameters passed to nextafter() are of type long double, the returned type Promoted is long double. If not, the returned type Promoted is double.

nextafter() parameters

  • xThe basic value.

  • yThe approximate value of the return value.

nextafter() return value

The nextafter() function returns the next representable value after x in the direction of y.

Example1The nextafter() function in C ++How does it work?

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    double x = 0.0, y = 1.0;
    double resultInDouble = nextafter(x, y);
    cout << "nextafter(x, y) = " << resultInDouble << endl;
    return 0;
}

The output when running the program is:

nextafter(x, y) = 4.94066e-324

Example2The nextafter() function is used for different types of parameters

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    float y = 1.0;
    double x = INFINITY;
    double result = nextafter(x, y);
    cout << "nextafter(x, y) = " << result << endl;
    return 0;
}

The output when running the program is:

nextafter(x, y) = 1.79769e+308

C++ Library Function <cmath>