Summary of the C language Rounding Method
The C language has the following methods to take an integer: 1. assign a value directly to an integer variable.Int I = 3.5; or I = (int) 3.5;
This method removes the decimal part.
2. Integer Division operator '/' is an integer division operator.
'/' Itself has the integer/int function. However, the integer division round-robin result is related to the C compiler.
3. Use the floor function
Floor (x) returnsThe maximum integer less than or equal to x. For example:
Floor (3.5) = 3
Floor (-3.5) =-4
4. Use the ceil Function
Ceil (x) returnsMinimum integer greater than x. For example:
Ceil (3.5) = 4
Ceil (-3.5) =-3
Floor () isRound to negative infinity, Floor (-3.5) =-4;
Ceil () isRound to positive infinity, Ceil (-3.5) =-3.
However, in C, the ceil and floor () functions return the double type.
5. rounded up
I found a simple rounded up method on the Internet;
Here we use <> to show the rounded up and [] to show the rounded down. We can prove that:
= [(N-1)/M] + 1 (0 <M <= n m, N, Z)
Without losing its universality, weSet N = Mk + r (0 <= r <M, kε Z),
(1)When r> 0,
Left side: = <(Mk + r)/M> = = K + = K + 1
Right: [(N-1)/M] + 1 = [(Mk + R-1)/M] + 1 = [k + (r-1) /M] + 1 = k + 1 + [(r-1)/M] = k + 1
(2)When r = 0,
Left side: = K
Right side:
[(N-1)/M] + 1 = [(Mk-1)/M] + 1 = [(M (k-1) + M-1)/M] + 1
= [K-1 + (M-1)/M] + 1 = k + [(M-1)/M]
= K
In conclusion, the proposition is proved.
With this formula, we can calculate it in the Code as follows:
Int nn = (N-1)/M + 1
'/' Is rounded down.