在JavaScript中,我如何得到:
一个给定整数除另一个整数的整数倍是多少? 其余的呢?
在JavaScript中,我如何得到:
一个给定整数除另一个整数的整数倍是多少? 其余的呢?
当前回答
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。
const idivmod = (a, b) => [a/b |0, a%b];
还有一项关于这个问题的提案 模量和附加整数数学
我不是位运算的专家,但这里有另一种方法来获得整个数字:
var num = ~~(a / b);
这也适用于负数,而Math.floor()将以错误的方向舍入。
这似乎也是正确的:
var num = (a / b) >> 0;
你也可以使用三元来决定如何处理正整数值和负整数值。
var myInt = (y > 0) ? Math.floor(y/x) : Math.floor(y/x) + 1
如果这个数字是正数,就没有问题。如果这个数字是负数,它会加1,因为数学。地板处理否定。
floor(operation)返回操作的四舍五入值。
第一个问题的例子:
Const x = 5; Const y = 10.4; const z =数学。地板(x + y); console.log (z);
第二个问题的例子:
Const x = 14; Const y = 5; const z =数学。地板(x % y); console.log (x);