在 JavaScript 中使用模数 (%) 运算符的正确方法是什么?
在 JavaScript 中,% 运算符的行为似乎非常奇怪。 我尝试了以下操作:
>>> (0 - 11) % 12
-11
为什么它返回 -11 而不是 1(如在 Python 中)?
我确信我正在做或期待错误,但文档没有告诉我什么。
In JavaScript the % operator seems to behave in a very weird manner. I tried the following:
>>> (0 - 11) % 12
-11
Why does it return -11 instead of 1 (as in Python)?
I am sure I am doing or expecting something wrong, but the docs don't tell me what.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
根据指定语言的方式,它的行为正确(例如 ECMA 262),其中它被称为余数运算符而不是模运算符。 从规格来看:
在您的情况下,
n/d
为负数,因此结果为负数。有关更多详细信息,请参阅关于模的维基百科条目,包括具有术语行为的语言列表的结果的符号。
It's behaving correctly according to the way the language is specified (e.g. ECMA 262), where it's called the remainder operator rather than the modulus operator. From the spec:
In your case
n/d
is negative, so the result is negative.See the Wikipedia entry on modulo for more details, including a list of languages with the behaviour in terms of the sign of the result.
有两种类似的运算:取模和取余。 模代表更多的数学用途,余数更多地代表 IT 用途。
假设我们有两个整数,a 和 b。
MOD(a, b) 将返回与 b 具有相同符号的结果。
REM(a, b) 将返回与 a 符号相同的结果。
- 这就是在 C/C++/C# 中实现的 % 运算符,并且经常被混淆地称为“mod”。
您也可以这样想:
MOD(a, b) 将找到 b 的最大整数倍(称之为“ c") 小于 a,并返回 (a - c)。
例如MOD(-340,60) 我们发现c = -360 是小于-340 的60 的最大倍数。 所以我们这样做 (-340 - (-360)) = 20。
REM(a, b) 将返回一个值,使得 (DIV(a,b) * b) + REM(a, b) = a,其中 DIV( ) 表示整数除法。
因此,对于 r = REM(-340, 60)
-340 = DIV(-340,60) * 60 + r
= -5 * 60 + r
= r - 300
解出 r = -40。
There are two similar operations: modulo and remainder. Modulo represents a more mathematical usage, and remainder more IT usage.
Assume we have two integers, a and b.
MOD(a, b) will return a result which has the same sign as b.
REM(a, b) will return a result which has the same sign as a.
- this is what is implemented in C/C++/C# as the % operator and often confusingly called "mod"
You can think of it like this too:
MOD(a, b) will find the largest integer multiple of b (call it "c") that is smaller than a, and return (a - c).
e.g. MOD(-340,60) we find c = -360 is the largest multiple of 60 that is smaller than -340. So we do (-340 - (-360)) = 20.
REM(a, b) will return a value such that (DIV(a,b) * b) + REM(a, b) = a, where DIV() represents integer division.
So for r = REM(-340, 60)
-340 = DIV(-340,60) * 60 + r
= -5 * 60 + r
= r - 300
This solves to give us r = -40.
-11 < 12,所以我“假设”它们实际上并没有分开:
所以 -11 = 0x12 -11
尝试一下 (0-13) % 12
-11 < 12, so i 'suppose' they don't actually divide:
So -11 = 0x12 -11
Have a try with (0-13) % 12
你说 MOD(a,b) 将返回与 b 符号相同的结果,但又说它返回 (ac),其中 c 小于 a。 第二个定义意味着它始终返回正数。 是哪一个?
You say MOD(a,b) will return a result with the same sign as b, but then say that it returns (a-c) where c is smaller than a. This second definition means that it always returns a positive number. Which is it?
数学模块中的 fmod 在 python 中表现正确:
-11 是正确答案。
fmod from the math module behaves correctly in python:
-11 is the correct answer..