Home » C++ programming language

nextafter() function with example in C++

C++ nextafter() function: Here, we are going to learn about the nextafter() function with example of cmath header in C++ programming language?
Submitted by IncludeHelp, on April 28, 2019

C++ nextafter() function

nextafter() function is a library function of cmath header, it is used to get the next representable value after the given first number in the direction of given second number, it accepts two numbers (x, y) and returns the next representable value after x in the direction of y.

Syntax of nextafter() function:

    nextafter(x, y);

Parameter(s): x, y – are the numbers to be used to find the next representable value of x in the direction of y.

Return value: float/double/long double – based on the input type, it returns the next representable value of x.

Example:

    Input:
    float x = 0.0;
    float y = 0.1;

    Function call:
    nextafter(x,y);    
    
    Output:
    1.4013e-45

C++ code to demonstrate the example of nextafter() function

// C++ code to demonstrate the example of 
// nextafter() function

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

// main() section
int main()
{
    float x;
    float y;
    
    x = 0.0;
    y = 0.1;
    cout<<"nextafter("<<x<<","<<y<<"): "<<nextafter(x,y);
    cout<<endl;

    x = 0.0;
    y = 1.1;
    cout<<"nextafter("<<x<<","<<y<<"): "<<nextafter(x,y);
    cout<<endl;    

    x =  0.0;
    y = -1.0;
    cout<<"nextafter("<<x<<","<<y<<"): "<<nextafter(x,y);
    cout<<endl;

    x = 0.1;
    y = 0.1;
    cout<<"nextafter("<<x<<","<<y<<"): "<<nextafter(x,y);
    cout<<endl;
   
    return 0;
}

Output

nextafter(0,0.1): 1.4013e-45
nextafter(0,1.1): 1.4013e-45
nextafter(0,-1): -1.4013e-45
nextafter(0.1,0.1): 0.1

Reference: C++ nextafter() function



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.