在JavaScript中,我如何得到:
一个给定整数除另一个整数的整数倍是多少? 其余的呢?
在JavaScript中,我如何得到:
一个给定整数除另一个整数的整数倍是多少? 其余的呢?
当前回答
对于某个数y和某个除数x,计算商(商)[1]和余数(余)为:
const quotient = Math.floor(y/x);
const remainder = y % x;
例子:
const quotient = Math.floor(13/3); // => 4 => the times 3 fits into 13
const remainder = 13 % 3; // => 1
[1]由一个数除以另一个数得到的整数
其他回答
Alex Moore-Niemi的评论作为回答:
对于从谷歌搜索divmod的ruby,你可以这样实现它:
function divmod(x, y) {
var div = Math.trunc(x/y);
var rem = x % y;
return [div, rem];
}
结果:
// [2, 33]
对于某个数y和某个除数x,计算商(商)[1]和余数(余)为:
const quotient = Math.floor(y/x);
const remainder = y % x;
例子:
const quotient = Math.floor(13/3); // => 4 => the times 3 fits into 13
const remainder = 13 % 3; // => 1
[1]由一个数除以另一个数得到的整数
我不是位运算的专家,但这里有另一种方法来获得整个数字:
var num = ~~(a / b);
这也适用于负数,而Math.floor()将以错误的方向舍入。
这似乎也是正确的:
var num = (a / b) >> 0;
const idivmod = (a, b) => [a/b |0, a%b];
还有一项关于这个问题的提案 模量和附加整数数学
function integerDivison(dividend, divisor){
this.Division = dividend/divisor;
this.Quotient = Math.floor(dividend/divisor);
this.Remainder = dividend%divisor;
this.calculate = ()=>{
return {Value:this.Division,Quotient:this.Quotient,Remainder:this.Remainder};
}
}
var divide = new integerDivison(5,2);
console.log(divide.Quotient) //to get Quotient of two value
console.log(divide.division) //to get Floating division of two value
console.log(divide.Remainder) //to get Remainder of two value
console.log(divide.calculate()) //to get object containing all the values