The C language has the following rounding methods:
1, the direct assignment to the integer variable. Such as:
int i = 2.5; or i = (int) 2.5;
This method uses the rounding up of the decimal part
2, the integer division operator in C + +"/"has a rounding function (int/int), But integer division is related to the rounding result of negative numbers and the C compiler used.
3, use the floor function. Floor (x) returns the largest integer that is less than or equal to X. such as:
floor (2.5) = 2
Floor ( -2.5) =-3
4, use the Ceil function. Ceil (x) returns the smallest integer greater than X. such as:
ceil (2.5) = 3
Ceil ( -2.5) =-2
Floor () is rounded to negative infinity, floor ( -2.5) = -3;ceil () is rounded to positive infinity, ceil (-2.5) =-2.
But in c the Ceil and floor () functions are returned as double types,
First find a simple upward rounding method on the Internet;
Here we use <> for rounding up, [] for rounding down, then how to represent this value?
We can prove that:
<n/m>=[(N-1)/m]+1 (0<m<=n,m,n∈z)
Without losing its generality, we set up N=mk+r (0<=r<m),
1) when r>0,
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
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
The proposition is to be proven.
With this formula, we can calculate this in the code:
int nn= (N-1)/M +1
.
Because the '/' is rounded down.
"Rounding up/rounding down" C language up or down function