Comparison of rounding functions for C + +
Rounding a number that contains a decimal point is a common requirement. There are similar rounding functions in C + +. There are floor () and ceil () functions in the header file of C + +. There are also round () functions in the STL. These three functions function as follows:
Function Name |
function Description |
2.1 |
2.9 |
-2.1 |
-2.9 |
Floor () |
Maximum integer not greater than the independent variable |
2 |
2 |
-3 |
-3 |
Ceil () |
Maximum integer not less than the argument |
3 |
3 |
-2 |
-2 |
Round () |
Rounding to Nearest integer |
2 |
3 |
-2 |
-3 |
As you can see from the function description,
(1) floor () will not be greater than the maximum number of arguments, so that the argument is 3.1 or 3.9 is no difference, the return is 3; The argument is 2.1 or 2.9 is no difference, return is-3;
(2) Ceil () takes the largest integer not less than the argument, so that the argument is 3.1 or 3.9, the return is 4, the argument is 2.1 or-2.9, and the return is-2;
(3) The Round () function, which is the rounding function we need, because it returns the nearest integer to the argument, the returned integer may be greater than or less than the original number, but must be the nearest integer to it.
Note: Floor (), the Ceil () function is included in the header file "Math.h", but the round () function is not included in the header file. Therefore, it is possible to implement the round () function by using the above principle to achieve rounding of numbers containing decimals.
Code implementation One:
int round_double(double number){ return (number > 0.0) ? (number + 0.5) : (number - 0.5); }
Code implementation Two:
int round_double(double number){ return (number > 0.0) ? floor(number + 0.5) : ceil(number - 0.5);}
C + + rounding