the C language has the following rounding methods:1. Direct assignment to integer variablesint I
= 3.5; or i = (int) 3.5;
This approach employs a fractional portion.
2, Integer division operator '/' rounding
the '/' itself has a rounding function (Int/int), but integer division is related to the rounding result of negative numbers and the C compiler used.
3. Using the floor function
Floor (x) returns the largest integer that is less than or equal to X . Such as:
Floor (3.5) = 3
Floor (-3.5) =-4
4. Using the Ceil function
ceil (x) returns the smallest integer greater than x . Such as:
ceil (3.5) = 4
Ceil (-3.5) = 3
Floor () is rounded to negative infinity , floor (-3.5) =-4;
ceil () is rounded to positive infinity , ceil (-3.5) =-3.
But in c the Ceil and floor () functions are returned as double types .
5. Rounding up Method
A simple upward rounding method is found on the Internet;
Here we use <> for rounding up, [] for rounding down, we can prove that:
<n/m>= [(N-1)/m]+1 (0 < M <= N m,n∈z)
without losing its generality, we set n = mk+r (0 <= R < m,k∈z),
(1) when R > 0 o'clock,
Left:<n/m> = < (mk+r)/M >= <k+r/m>= k+<r/m> = 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 o'clock,
Left:<n/m> = k
Right:
[(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 to be proven.
with this formula, we can calculate this in the code:
int nn = (N-1)/M +1
the "/" in the formula is rounded down.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Summary of C-language rounding method