What is nexttoward() in C?

The nexttoward() function produces the smallest possible value after a number in a given direction. The declaration of nexttoward() is shown below:

double nexttoward (double num, long double dir);

Or:

long double nexttowardl (long double num, long double dir);

Or:

float nexttowardf (float num, long double dir);

Parameters

  • num: The number of which the next representable floating point is required
  • dir: The direction of the floating point with respect to num

Return value

The nexttoward() function returns the next representable floating-point number after num in the direction of dir.

Library

To use the nexttoward() function, include the following library:

#include <math.h>

Example

Consider the code snippet below, which demonstrates the implementation of nexttoward():

#include <stdio.h>
#include <math.h>
int main() {
double a = 0.0;
long double b = 2.0;
long double c = -2.0;
double x = nexttoward(a, b);
double y = nexttoward(a, c);
printf("nexttoward ( %f, %Lf ) = ( %e) \n", a, b, x);
printf("nexttoward ( %f, %Lf ) = ( %e) \n", a, c, y);
return 0;
}

Explanation

The nexttoward() function is used in lines 10 and 11 to compute the next representable floating-point number after a in the direction of b and c.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved