Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What is nearbyint() in C?

Syed Muhammad Ali Mustafa

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.

The nearbyint() function casts the given double argument to an integral number in a double representation, based on the selected mode of rounding.

Library

#include<math.h>

Declaration

double nearbyint(double x);

Modes of rounding

We can specify the modes of rounding before calling nearbyint().

The four modes of rounding are as follows:

1. FE_TONEAREST

In this mode, the floating point value is rounded to the nearest integer.

2. FE_DOWNWARD

In this mode, nearbyint() returns the floor of the floating-point value.

3. FE_UPWARD

In this mode, nearbyint() returns the ceil of the floating-point value.

4. FE_TOWARDZERO

In this mode, nearbyint() returns the integer that is closer to zero.

Note: The default mode of rounding is FE_TONEAREST.

Code

#include <stdio.h>
#include <fenv.h> //header file for fesetround()
#include <math.h>
int main()
{
double num = 1.6;
printf("%f", nearbyint(num)); //rounding off the number
fesetround(FE_DOWNWARD);
num = 0.5;
printf("\n%f", nearbyint(num)); //calculating floor of number
fesetround(FE_UPWARD);
num = 0.3;
printf("\n%f", nearbyint(num)); //calculating ceil of number
fesetround(FE_TOWARDZERO);
num = -1.9;
printf("\n%f", nearbyint(num)); //return number closer to zero
return 0;
}

RELATED TAGS

c

CONTRIBUTOR

Syed Muhammad Ali Mustafa
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