rounding a number that contains a decimal point is a common requirement. Similar rounding functions are also available in C + +. There are floor () and ceil () functions in the header file of C + +. There is also a round () function in the STL. The function of these three functions is as follows:
|
|
|
|
|
|
Function name |
Function description |
2.1 |
2.9 |
-2.1 |
-2.9 |
Floor () |
The largest integer that is not greater than the argument |
2 |
2 |
-3 |
-3 |
Ceil () |
The largest integer that is not less than the independent variable |
3 |
3 |
-2 |
-2 |
Round () |
Rounded to the nearest adjacent integer |
2 |
3 |
-2 |
-3 |
As you can see from the description of the function,
(1) Floor () takes the largest integer not greater than the argument, so that the argument is 3.1 or 3.9 is no different, the return is 3; The argument is-2.1 or-2.9 is no different, and the return is-3;
(2) Ceil () takes the largest integer that is 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 rounded function we need, because it returns the nearest integer from the variable, the returned integer may or may be less than the original number, but it must be the nearest integer.
Note: Floor (), the Ceil () function is included in the header file "Math.h", but the round () function is not included in the header file. So you can implement the round () function on your own by using the above principles to achieve rounding of numbers that contain decimals.
Code implementation One:
int round_double (double)
{return
(number > 0.0)? (number + 0.5): (number-0.5);
}
1 2 3 4 1 2 3 4
Code implementation Two:
int round_double (Double) {return (number > 0.0)? floor (number + 0.5): Ceil (number-0.5);}