在JavaScript中,我如何得到:

一个给定整数除另一个整数的整数倍是多少? 其余的呢?


当前回答

var remainder = x % y;
return (x - remainder) / y;

其他回答

我不是位运算的专家,但这里有另一种方法来获得整个数字:

var num = ~~(a / b);

这也适用于负数,而Math.floor()将以错误的方向舍入。

这似乎也是正确的:

var num = (a / b) >> 0;

对于某个数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]由一个数除以另一个数得到的整数

计算页数可以一步完成: Math.ceil (x / y)

如果你只是用2的幂除法,你可以使用位运算符:

export function divideBy2(num) {
  return [num >> 1, num & 1];
}

export function divideBy4(num) {
  return [num >> 2, num & 3];
}

export function divideBy8(num) {
  return [num >> 3, num & 7];
}

(第一个是商,第二个是余数)

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);