Swift Learning notes-Basic Operators-finding the remainder operator

Source: Internet
Author: User

The remainder operation ( a % b ) is the number of times that the calculation is b just good enough to be able a to fill, returning the part that is more than that.

Attention:
The redundancy operation ( % ) is also called modulo operation in other languages. Strictly speaking, however, we look at the result of the operator's operation on negative numbers, and the "redundancy" is more appropriate than "modulo".

Let's talk about how the remainder is calculated 9 % 4 , and 4 How many times you calculate it will just fit 9 in:

Twice times, very good, that remainder is 1 (marked in orange)

In Swift, it can be expressed as:

9% 4    //equals 1

To get a % b The result, the % following equation is computed and output 余数 as the result:

A = (bx multiples) + remainder

When 倍数 the maximum value is taken, it will just fit into the a box.

To put 9 and 4 substitute into the equation, we have to 1 :

9 = (4x2) + 1

In the same way, let's calculate -9 % 4 :

-9% 4   //equals-1

To put -9 and 4 substitute the equation, -2 is the largest integer taken:

-9 = (4x-2) +-1

The remainder is -1 .

When you balance negative numbers b , b the symbols are ignored. This means that a % b the a % -b results are the same as the result.

Calculation of floating-point number for remainder

Unlike the C language and objective-c,swift, floating-point numbers can be redundant.

8% 2.5   //equals 0.5

In this example, the 8 2.5 3 0.5 result is a Double value, except for equal to remainder 0.5 .

Swift Learning notes-Basic Operators-finding the remainder operator

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.