English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ The usage and example of rint() function

C++ Library Function <cmath>

C ++The rint() function rounds the parameter to an integer value using the current rounding mode. The current rounding mode is determined by the function fesetround().

The rint() prototype [from C ++ 11Standard start]

double rint(double x);
float rint(float x);
long double rint(long double x);
double rint(T x); //For integer

The rint() function takes a single parameter and returns a value of type double, float, or long double. This function is in<cmath>Defined in the header file.

The rint() parameter

The rint() function takes a single parameter and rounds it to an integer.

The rint() return value

The rint() function uses the rounding direction specified by fegetround() to round the parameter x to an integer value and returns this value. By default, the rounding direction is set to "nearest". You can use the fesetround() function to set the rounding direction to other values.

Example1:How does the rint() function work in C ++How does it work in C?

#include <iostream>
#include <cmath>
#include <cfenv>
using namespace std;
int main()
{
    //By default, the rounding direction is the nearest direction, that is, fesetround(FE_TONEAREST)
    double x = 11.87, result;
    result = rint(x);
    cout << "Round to the nearest (" << x << ") = " << result << endl;
    
    //Choose the higher value for the midpoint
    x = 11.5;
    result = rint(x);
    cout << "Round to the nearest (" << x << ") = " << result << endl;
    // Set the rounding direction to DOWNWARD
    fesetround(FE_DOWNWARD);
    x = 11.87;
    result = rint(x);
    cout << "Floor rounding (" << x << ") = " << result << endl;
    
    // Set the rounding direction to UPWARD
    fesetround(FE_UPWARD);
    x = 33.32;
    result = rint(x);
    cout << "Round up (" << x << ") = " << result << endl;
    
    return 0;
}

When the program is run, the output is:

Round to the nearest (11.87) = 12
Round to the nearest (11.5) = 12
Floor rounding (11.8699) = 11
Round up (33.3201) = 34

Example2:The rint() function for integer type

#include <iostream>
#include <cmath>
#include <cfenv>
using namespace std;
int main()
{
    int x = 15;
    double result;
    
    // Set the rounding direction to DOWNWARD
    fesetround(FE_DOWNWARD);
    result = rint(x);
    cout << "Floor rounding (" << x << ") = " << result << endl;
    return 0;
}

When the program is run, the output is:

Floor rounding (15) = 15

For integer values, the rint function will return the same value as the input. Therefore, it is usually not used for integral values in practice.

C++ Library Function <cmath>