简体   繁体   English

为什么CoffeeScript使用%%代替模数而不是标准的javascript运算符%

[英]Why does CoffeeScript use %% for modulo instead of the standard javascript operator %

In the CoffeeScript documentation on operators it says that you can use %% for true mathematical modulo, but there is no explanation as to why this is different from the "modulo operator" % in JavaScript. 关于运算符CoffeeScript文档中,它说你可以使用%%作为真正的数学模,但是没有解释为什么这与JavaScript中的“模运算符” %不同。

Further down it says that a %% b in CoffeeScript is equivalent to writing (a % b + b) % b in JavaScript but this seem to produce the same results for most simple cases. 再往下说,CoffeeScript中a %% b相当于在JavaScript中编写(a % b + b) % b ,但这似乎对大多数简单情况产生相同的结果。

I did find the answer in another StackOverflow question and answer Javascript modulo not behaving and I wanted to share it for people who like me only looked for a "CoffeeScript" related explanations and thus have a hard time finding the correct answer. 我确实在另一个StackOverflow问题中找到答案并回答Javascript模数不行为我想分享给那些喜欢我的人只寻找“CoffeeScript”相关的解释,因此很难找到正确的答案。

The reason for using a %% b which compiles to (a % b + b) % b is that for negative number, like -5 % 3 , JavaScript will produce a negative number -5 % 3 = -2 while the correct mathematical answer should be -5 % 3 = 1 . 使用编译为(a % b + b) % b a %% b的原因是对于负数,如-5 % 3 ,JavaScript将产生负数-5 % 3 = -2而正确的数学答案应为-5 % 3 = 1

The accepted answer refers to an article on the JavaScript modulo bug which explains it well. 接受的答案是指一篇关于JavaScript模数错误的文章,它解释得很好。

Made no sense for me at first, so I believe it needs an example 起初对我没有任何意义,所以我认为它需要一个例子

check = (a,b) ->
  c = (b*Math.floor(a/b)) + a%b
  d = (b*Math.floor(a/b)) + a%%b
  console.log(
    [c, c == a]
    [d, d == a]
  )

check  78, 33 # [ 78, true ] [ 78, true ]
check -78, 33 # [ -111, false ] [ -78, true ]

###
 78 mod 33 = 12
-78 mod 33 = 21

check:  78 = 33 *  2 + 12
check: -78 = 33 * -3 + 21
###

Looks like modulo is a mathematical trick to be able to use one formula for all numbers instead of one for negatives and second for positives. 看起来modulo是一个数学技巧,能够为所有数字使用一个公式,而不是一个用于负数,第二个用于正数。 Don't know if it's more than just a trick and have some intrinsic meaning though. 不知道它不仅仅是一个技巧,而且具有一些内在意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM