"Rounding up/rounding down" C language up or down function

Source: Internet
Author: User
Tags floor function integer division

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.