What is the purpose of the round function in C++?
In C++, the round() function is used to round a floating point number to the nearest integer. It takes a floating point value and returns the closest integer value as a double. The prototype of the round() function is as follows:
double round(double x);
- X: A floating point number needs to be rounded.
The working principle of the round() function is as follows:
- The round() function will round down (discard the decimal part) if the decimal part of x is less than 0.5.
- The round() function will round up (round up to the next whole number) if the decimal part of x is greater than or equal to 0.5.
Below are a few examples of the round() function:
#include <iostream>
#include <cmath>
int main() {
double x = 3.7;
double y = 4.3;
std::cout << "Round of " << x << " is " << round(x) << std::endl; // 输出:Round of 3.7 is 4
std::cout << "Round of " << y << " is " << round(y) << std::endl; // 输出:Round of 4.3 is 4
return 0;
}
In the example above, round(x) rounds 3.7 to 4 and round(y) rounds 4.3 to 4.