Summary of the C language Rounding Method

Source: Internet
Author: User
Tags floor function integer division

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.


 

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.