为什么模运算符(%)不同的C和Ruby之间的负整数的行为? [英] Why is the behavior of the modulo operator (%) different between C and Ruby for negative integers?
问题描述
我在这里运行在一些code。我试图 -40%3
。它给我的输出 2
。当我下进行同样的操作,我得到:
I was running some code in here. I tried -40 % 3
. It gives me the output 2
. when I performed the same operation in C, I get:
int i = (-40) % 3
printf("%d", i);
输出
-1
如何在内部进行取模运算两种语言?
How are both languages performing the modulo operation internally?
推荐答案
维基说:
由于两个正数, A
(股息)和 N
(中除数),一模n (简写为MOD n)是由n个 A的欧几里德除法的余
。结果
.... 当任 A
或 N
是否定的,天真的定义分解和编程语言不同这些值是如何定义的。
Given two positive numbers,
a
(the dividend) andn
(the divisor), a modulo n (abbreviated as a mod n) is the remainder of the Euclidean division ofa by n
.
.... When eithera
orn
is negative, the naive definition breaks down and programming languages differ in how these values are defined.
现在的问题是,为什么 -40%3
是 2
在Ruby或者换句话说什么是数学落后吗?
Now the question is why -40 % 3
is 2
in Ruby or in other words what is the mathematics behind it ?
让我们先从欧几里德师其中指出:
给定两个整数 A
和 N
与ñ≠0
,存在唯一的整数①
和研究
,使得 A = N * q + R
和 0≤为r | N |
,其中 | N |
表示的绝对值n
。
Given two integers
a
andn
, withn ≠ 0
, there exist unique integersq
andr
such thata = n*q + r
and0 ≤ r < |n|
, where|n|
denotes the absolute value ofn
.
现在注意商数的两个定义:
Now note the two definitions of quotient:
1
高德纳的描述其中商是由地板功能定义地板师 q =楼(A / N)
,其余的研究
是结果
1.
Donald Knuth described floored division where the quotient is defined by the floor function q=floor(a/n)
and the remainder r
is
这里的商(①
)总是向下(即使它已经是负)圆润,其余的(研究
)具有相同的符号作为除数。
Here the quotient (q
) is always rounded downwards (even if it is already negative) and the remainder (r
) has the same sign as the divisor.
2
一些实现定义商作为
Q = SGN(一)地板(| A | / N)。
whre SGN
是符号函数
q = sgn(a)floor(|a| / n)
whre sgn
is signum function.
和剩余(研究
)具有相同的符号股息( A
)。
and the remainder (r
) has the same sign as the dividend(a
).
现在一切都取决于①
:
- 如果实现去与定义
1
并定义①
为楼(A / N )
则值40%3
是1
和-40%3
是2
。这似乎是在这里为Ruby的情况。 - 如果实现去与定义
2
并定义①
为SGN(一)楼(| A | / N)
,然后价值40%3
是1
和-40%3
是1
。这似乎是在这里为C和Java的情况。
- If implementation goes with definition
1
and defineq
asfloor(a/n)
then the value of40 % 3
is1
and-40 % 3
is2
. Which here seems the case for Ruby.- If implementation goes with definition
2
and defineq
assgn(a)floor(|a| / n)
, then the value of40 % 3
is1
and-40 % 3
is-1
. Which here seems the case for C and Java.
这篇关于为什么模运算符(%)不同的C和Ruby之间的负整数的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!