【问题标题】:Modulo operator reports different results with negative value [duplicate]模运算符报告具有负值的不同结果[重复]
【发布时间】:2014-06-01 01:20:08
【问题描述】:

我在 google/wolfram alpha 中输入这个:

-15 % 360

我得到345

当我在 javascript 中执行此操作时,我得到 -15

https://www.google.com/search?q=-15%20%%20360

http://www.wolframalpha.com/input/?i=-15+mod+360

http://jsfiddle.net/BG3jW/

【问题讨论】:

  • 自己运行它,看看我已经在 Dolphin、Safari、Chrome、Firefox、IE、Opera 等人类已知的所有环境中进行了测试
  • 顺便说一句,Coffeescript 使用 %% 运算符修复了这个问题。
  • 它没有“损坏”。它在ECMAScript specification 中有很好的定义。
  • 模必须满足 a%b=a-(a/b)*b 相对于整数除法。现在必须决定 (-15)/360、0 或 -1 的值哪个更自然。 0 给出负余数,-1 给出正余数。 JS 决定在整数除法中向 0 舍入,从而给出负余数。

标签: javascript math operator-keyword modulo


【解决方案1】:

% (remainder) 运算符在 JavaScript 中没有“损坏”,即使结果可能出乎意料 - 尤其是在预期更严格的数学模运算时。

ECMAScript 中明确定义了该行为。见11.5.3 Applying the % Operator:

% [remainder] 运算符从隐含的除法中产生其操作数的余数;左操作数是被除数,右操作数是除数..

.. 被除数 n 和除数 d 的 [floating-point] 余数 r 由数学关系 r = n - (d * q) 定义,其中 q 是一个整数,仅当 n 为负时/d 是负数,只有当 n/d 为正数时为正数 ..

以这种方式,它的行为方式与 remainder operator in Java 或 C#(对于整数输入)相同。

有人认为should be referred to as the remainder operator 是为了避免这种混淆:ES5 确实隐含地将其称为“余数运算符”,但 Mozilla JavaScript Reference 将其称为“模数运算符”。


另见Modulus operation with negatives values - weird thing?,它实际上是从另一个角度看待“破碎”。

【讨论】:

    猜你喜欢
    • 2011-11-27
    • 1970-01-01
    • 2018-10-31
    • 1970-01-01
    • 1970-01-01
    • 2012-02-28
    • 1970-01-01
    相关资源
    最近更新 更多