在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]由一个数除以另一个数得到的整数
其他回答
它总是截断为零。 不知道是不是太迟了,但我要说的是:
function intdiv(dividend, divisor) {
divisor = divisor - divisor % 1;
if (divisor == 0) throw new Error("division by zero");
dividend = dividend - dividend % 1;
var rem = dividend % divisor;
return {
remainder: rem,
quotient: (dividend - rem) / divisor
};
}
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);
对于某个数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]由一个数除以另一个数得到的整数
您可以使用parseInt函数来获得截断的结果。
parseInt(a/b)
要得到余数,使用mod操作符:
a%b
parseInt有一些陷阱字符串,以避免使用基数参数以10为基数
parseInt("09", 10)
在某些情况下,数字的字符串表示可以是科学符号,在这种情况下,parseInt将产生错误的结果。
parseInt(100000000000000000000000000000000, 10) // 1e+32
这个调用的结果是1。
你也可以使用三元来决定如何处理正整数值和负整数值。
var myInt = (y > 0) ? Math.floor(y/x) : Math.floor(y/x) + 1
如果这个数字是正数,就没有问题。如果这个数字是负数,它会加1,因为数学。地板处理否定。