Remainder operator
In most languages,% is the remainder operator. Its functionality is very simple, but it only supports redundancy between positive numbers of type int. For example 10% 3 = 1.
Strictly speaking, the definition of redundancy between positive integers is as follows:
For any a,b∈n*, define m = a% B, where M satisfies:
A = b * m + R and 0 <= R < b
Development of redundancy usage scenarios in swift
The redundancy in Swift is no longer an operator between two positive int types. Not only can the negative number be redundant, but also the floating-point number can be obtained.
Floating-point rules for finding remainder
First, it does not consider the symbol to see a floating point to find the remainder, and its definition is very similar to the balance between positive integers. Not to mention it here, for example.
var c = 10.5 % 3println("c = \(c)"// 输出结果是c = 1.5
It is important to note that the redundancy operator does not require that the two end variable types be strictly equal. So there is no problem with this writing. Of course, the balance between two floating-point numbers is also possible.
The rule of negative integer seeking redundancy
For example, I would like to ask 10-3 or-10 3 results, the answer is not as easy as floating-point to find redundancy.
In fact, we can look back at the definition of positive integer redundancy:
A = b * m + R
A simple simplification will give you the following two equations:
A = (-B) * (-M) + R//pair B * M equivalent transform
-A = b * (-M) + (-r)//multiply by-1 on both sides of the equation
Therefore, the rule of negation of negative numbers is also very simple, that is,
The number to the right of the% number takes the opposite number, the result of the operation is unchanged
The number to the left of the% number takes the opposite number, the result of the operation is reversed
As a result, you can get the following four operations:
1031 //我们都知道的等式一-103 = -1 //和等式一结果互为相反数10 % -31 //和等式一结果相等-10 % -3 = -1 //和等式二结果相等
If you are still not at ease, you can also write a very simple program to verify:
forvar a = 0; a < 100; ++a{ println("\(a) % 5 = \(a % 5)") println("\(a) % -5 = \(a % -5)") println("\(-a) % 5 = \(-a % 5)")}
You must use ++a instead of a++, or the compiler will make an error. -A uses the yin-yang operator to take the opposite number to the value of a.
Negative floating-point number to seek remainder
The answer can be obtained by using negative integers and floating-point numbers to find the remainder rule.
Summarize:
The redundancy operator in Swift is a powerful feature. However, in most cases it may still be used between positive integers.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Introduction to Swift (eight)--powerful redundancy operator