JavaScript 找到整数的商和余数
在本文中,我们将在JavaScript中找到整数的商和余数。有多种方法可以将一个整数除以另一个数并得到它的商和余数。
- 使用Math.floor()方法
- 使用
~~操作符 - 右移>> >操作符
示例1: 此示例使用Math.floor()函数来计算除数。
let a = 39;
let b = 5;
function Geeks() {
console.log("quotient = " + Math.floor(a / b))
console.log("remainder = " + a % b);
}
Geeks()
输出
quotient = 7
remainder = 4
示例2: 该示例使用二进制 ~~ 运算符 来计算除数。
let a = 39;
let b = 5;
function Geeks() {
let num = ~~(a / b);
console.log("quotient = " + num)
console.log("remainder = " + a % b);
}
Geeks()
输出
quotient = 7
remainder = 4
示例3: 此示例使用 右移 >> 运算符来计算除数。
let a = 39;
let b = 5;
function Geeks() {
let num = (a / b) >> 0;
console.log("quotient = " + num)
console.log("remainder = " + a % b);
}
Geeks()
输出
quotient = 7
remainder = 4
极客教程