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