根据谷歌计算器(-13)% 64 = 51。

根据Javascript(参见这个JSBin),它是-13。

我怎么解决这个问题?


当前回答

我还要处理négative a和- n

 //best perf, hard to read
   function modul3(a,n){
        r = a/n | 0 ;
        if(a < 0){ 
            r += n < 0 ? 1 : -1
        }
        return a - n * r 
    }
    // shorter code
    function modul(a,n){
        return  a%n + (a < 0 && Math.abs(n)); 
    }

    //beetween perf and small code
    function modul(a,n){
        return a - n * Math[n > 0 ? 'floor' : 'ceil'](a/n); 
    }

其他回答

Number.prototype.mod = function (n) {
  "use strict";
  return ((this % n) + n) % n;
};

摘自本文:JavaScript Modulo Bug

一个“mod”函数,返回一个正的结果。

var mod = function (n, m) {
    var remain = n % m;
    return Math.floor(remain >= 0 ? remain : remain + m);
};
mod(5,22)   // 5
mod(25,22)  // 3
mod(-1,22)  // 21
mod(-2,22)  // 20
mod(0,22)   // 0
mod(-1,22)  // 21
mod(-21,22) // 1

当然

mod(-13,64) // 51

如果x是整数,而n是2的幂,则可以使用x & (n - 1)而不是x % n。

> -13 & (64 - 1)
51 

虽然它没有像你期望的那样运行,但这并不意味着JavaScript没有“运行”。这是JavaScript为模数计算所做的选择。因为根据定义,两个答案都有意义。

请看维基百科。您可以在右边看到不同的语言如何选择结果的符号。

接受的答案让我有点紧张,因为它重用了%操作符。如果Javascript在未来改变了行为呢?

下面是一个不重用%的解决方案:

function mod(a, n) {
    return a - (n * Math.floor(a/n));
}

mod(1,64); // 1
mod(63,64); // 63
mod(64,64); // 0
mod(65,64); // 1
mod(0,64); // 0
mod(-1,64); // 63
mod(-13,64); // 51
mod(-63,64); // 1
mod(-64,64); // 0
mod(-65,64); // 63