根据谷歌计算器(-13)% 64 = 51。
根据Javascript(参见这个JSBin),它是-13。
我怎么解决这个问题?
根据谷歌计算器(-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);
}
其他回答
这不是一个错误,有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
我还要处理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
虽然它没有像你期望的那样运行,但这并不意味着JavaScript没有“运行”。这是JavaScript为模数计算所做的选择。因为根据定义,两个答案都有意义。
请看维基百科。您可以在右边看到不同的语言如何选择结果的符号。
JavaScript中的%操作符是余数操作符,而不是模数操作符(主要区别在于负数的处理方式):
-1 % 8 // -1,不是7