nearbyint() Function with Example in C++

C++ nearbyint() function: Here, we are going to learn about the nearbyint() function with example of cmath header in C++ programming language.
Submitted by IncludeHelp, on May 25, 2020

C++ nearbyint() function

nearbyint() function is a library function of cmath header, it is used to round the given value to an integral value based on the specified direction by fegetround() function. It accepts a value and returns the rounded integral value.

Syntax of nearbyint() function:

C++11:

     double nearbyint (double x);
      float nearbyint (float x);
long double nearbyint (long double x);
     double nearbyint (T x);

Parameter(s):

  • x – represents the value to round.

Return value:

It returns value rounded to nearby integral.

Example:

    Input:
    double x = 123.4;
    
    Function call:
    nearbyint(x);
    
    Output:
    123

    Input:
    double x = 123.5;
    
    Function call:
    nearbyint(x);
    
    Output:
    124

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

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

#include <iostream>
#include <cmath>
#include <fenv.h> // for fegetround()
using namespace std;

int main()
{
    double x = 0.0;

    cout << "Specified rounding is: ";
    switch (fegetround()) {
    case FE_DOWNWARD:
        cout << "Downward" << endl;
        break;
    case FE_TONEAREST:
        cout << "To-nearest" << endl;
        break;
    case FE_TOWARDZERO:
        cout << "Toward-zero" << endl;
        break;
    case FE_UPWARD:
        cout << "Upward" << endl;
        break;
    default:
        cout << "Unknown" << endl;
    }

    x = 123.4;
    cout << "nearbyint(" << x << "): " << nearbyint(x) << endl;

    x = 123.5;
    cout << "nearbyint(" << x << "): " << nearbyint(x) << endl;

    x = 123.6;
    cout << "nearbyint(" << x << "): " << nearbyint(x) << endl;

    x = -123.4;
    cout << "nearbyint(" << x << "): " << nearbyint(x) << endl;

    x = -123.5;
    cout << "nearbyint(" << x << "): " << nearbyint(x) << endl;

    x = -123.6;
    cout << "nearbyint(" << x << "): " << nearbyint(x) << endl;

    return 0;
}

Output

Specified rounding is: To-nearest
nearbyint(123.4): 123
nearbyint(123.5): 124
nearbyint(123.6): 124
nearbyint(-123.4): -123
nearbyint(-123.5): -124
nearbyint(-123.6): -124

Reference: C++ nearbyint() function




Comments and Discussions!

Load comments ↻






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