Summary of C-language rounding method

Source: Internet
Author: User

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

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.