English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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().
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() function takes a single parameter and rounds it to an integer.
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.
#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
#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.