Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What is nearbyintf in C?

Samia Ishaque

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

The nearbyintf() function in C is used to round-off a floating-point number to the nearest integer. The function is defined in the <math.h> header file.

To use the nearbyintf() function, you need to include the <math.h> library at the beginning of your program. Below is an example of how you can do this:

#include<math.h>

The nearbyintf() function in C is defined in the <math.h> header file as shown below:

float nearbyintf( float arg );

Parameters

The nearbyintf() function takes one argument arg of type float as input.

Return value

The nearbyintf() function, if executed successfully, returns the round-off value of arg by rounding off to the nearest integer. However, if arg is Not a Number (NaN), the return value for nearbyintf() is also NaN.

Example

Below is an example of how you can use nearbyintf(), given that arg = 4.5:

#include<stdio.h>
#include<math.h>
#include <fenv.h>
int main() {
int rounding_dir = fegetround();
printf("The rounding direction is: %d\n", rounding_dir);
printf("nearbyintf(2.5) = %.1f ", nearbyintf(4.5));
return 0;
}

Explanation

The nearbyintf() functions rounds-off arguments using the current rounding direction set for the machine you are working on. You can find out the rounding direction mode for your machine using the fegetround() function. The fegetround() function returns integer values that each correspond to a floating-point rounding macro. The table below highlights what each integer represents. The way in which the number is rounded-off in the code above depends on the current rounding mode that is printed in the code.

Integer

Current rounding direction

-1

Not determinable

0

Rounding toward 0

1

Rounding toward nearest number

2

Rounding toward positive infinity

3

Rounding toward negative infinity

RELATED TAGS

c

CONTRIBUTOR

Samia Ishaque
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring