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

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

我怎么解决这个问题?


当前回答

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

摘自本文:JavaScript Modulo Bug

其他回答

这不是一个错误,有3个函数来计算模,你可以使用一个适合你的需要(我建议使用欧几里得函数)

截断小数部分函数

console.log(  41 %  7 ); //  6
console.log( -41 %  7 ); // -6
console.log( -41 % -7 ); // -6
console.log(  41 % -7 ); //  6

整部函数

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

console.log( parseInt( 41).mod( 7) ); //  6
console.log( parseInt(-41).mod( 7) ); //  1
console.log( parseInt(-41).mod(-7) ); // -6
console.log( parseInt( 41).mod(-7) ); // -1

欧几里得函数

Number.prototype.mod = function(n) {
    var m = ((this%n)+n)%n;
    return m < 0 ? m + Math.abs(n) : m;
};

console.log( parseInt( 41).mod( 7) ); // 6
console.log( parseInt(-41).mod( 7) ); // 1
console.log( parseInt(-41).mod(-7) ); // 1
console.log( parseInt( 41).mod(-7) ); // 6
Number.prototype.mod = function (n) {
  "use strict";
  return ((this % n) + n) % n;
};

摘自本文:JavaScript Modulo Bug

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

> -13 & (64 - 1)
51 

一个“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

修正负模(提醒操作符%)

简化使用ES6箭头功能,没有危险的扩展数字原型

Const mod = (n, m) => (n % m + m) % m; console.log (mod (-90, 360));// 270(不是-90)