在JavaScript中,我如何得到:
一个给定整数除另一个整数的整数倍是多少? 其余的呢?
在JavaScript中,我如何得到:
一个给定整数除另一个整数的整数倍是多少? 其余的呢?
当前回答
Alex Moore-Niemi的评论作为回答:
对于从谷歌搜索divmod的ruby,你可以这样实现它:
function divmod(x, y) {
var div = Math.trunc(x/y);
var rem = x % y;
return [div, rem];
}
结果:
// [2, 33]
其他回答
我通常使用:
const quotient = (a - a % b) / b;
const remainder = 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
我在Firefox上做了一些速度测试。
-100/3 // -33.33..., 0.3663 millisec
Math.floor(-100/3) // -34, 0.5016 millisec
~~(-100/3) // -33, 0.3619 millisec
(-100/3>>0) // -33, 0.3632 millisec
(-100/3|0) // -33, 0.3856 millisec
(-100-(-100%3))/3 // -33, 0.3591 millisec
/* a=-100, b=3 */
a/b // -33.33..., 0.4863 millisec
Math.floor(a/b) // -34, 0.6019 millisec
~~(a/b) // -33, 0.5148 millisec
(a/b>>0) // -33, 0.5048 millisec
(a/b|0) // -33, 0.5078 millisec
(a-(a%b))/b // -33, 0.6649 millisec
以上是基于每种方法的1000万次试验。
结论:使用(a/b>>0)(或(~~(a/b))或(a/b|0))可获得20%左右的效率提升。还要记住,它们都与数学不一致。地板,当a/b<0 && a%b!=0。
您可以使用parseInt函数来获得截断的结果。
parseInt(a/b)
要得到余数,使用mod操作符:
a%b
parseInt有一些陷阱字符串,以避免使用基数参数以10为基数
parseInt("09", 10)
在某些情况下,数字的字符串表示可以是科学符号,在这种情况下,parseInt将产生错误的结果。
parseInt(100000000000000000000000000000000, 10) // 1e+32
这个调用的结果是1。
var remainder = x % y;
return (x - remainder) / y;