JavaScript 中的整数除法余数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4228356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Integer division with remainder in JavaScript?
提问by Yarin
In JavaScript, how do I get:
在JavaScript 中,我如何获得:
- The whole number of times a given integer goes into another?
- The remainder?
- 给定整数进入另一个整数的次数?
- 其余的?
回答by Mark Elliot
For some number y
and some divisor x
compute the quotient (quotient
) and remainder (remainder
) as:
对于某些数字y
和某些除数,x
计算商 ( quotient
) 和余数 ( remainder
) 为:
var quotient = Math.floor(y/x);
var remainder = y % x;
回答by user113716
I'm no expert in bitwise operators, but here's another way to get the whole number:
我不是按位运算符的专家,但这是获得整数的另一种方法:
var num = ~~(a / b);
This will work properly for negative numbers as well, while Math.floor()
will round in the wrong direction.
这也适用于负数,但Math.floor()
会朝错误的方向舍入。
This seems correct as well:
这似乎也是正确的:
var num = (a / b) >> 0;
回答by KalEl
I did some speed tests on Firefox.
我在 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
The above is based on 10 million trials for each.
以上基于每个试验 1000 万次。
Conclusion:Use (a/b>>0)
(or (~~(a/b))
or (a/b|0)
) to achieve about 20% gain in efficiency. Also keep in mind that they are all inconsistent with Math.floor
, when a/b<0 && a%b!=0
.
结论:使用(a/b>>0)
(或(~~(a/b))
或(a/b|0)
)可实现约 20% 的效率增益。还要记住,它们都与Math.floor
, when不一致a/b<0 && a%b!=0
。
回答by Oriol
ES6 introduces the new Math.trunc
method. This allows to fix @MarkElliot's answerto make it work for negative numbers too:
ES6 引入了新Math.trunc
方法。这允许修复@MarkElliot 的答案,使其也适用于负数:
var div = Math.trunc(y/x);
var rem = y % x;
Note that Math
methods have the advantage over bitwise operators that they work with numbers over 231.
请注意,Math
与按位运算符相比,方法的优势在于它们可以处理超过 2 31 的数字。
回答by gammax
var remainder = x % y;
return (x - remainder) / y;
回答by Wolf Elkan
I normally use:
我通常使用:
const quotient = (a - a % b) / b;
const remainder = a % b;
It's probably not the most elegant, but it works.
它可能不是最优雅的,但它有效。
回答by édipo Costa Rebou?as
You can use the function parseInt
to get a truncated result.
您可以使用该函数parseInt
来获得截断的结果。
parseInt(a/b)
To get a remainder, use mod operator:
要获得余数,请使用 mod 运算符:
a%b
parseInt have some pitfalls with strings, to avoid use radix parameter with base 10
parseInt 有一些字符串陷阱,以避免使用基数为 10 的基数参数
parseInt("09", 10)
In some cases the string representation of the number can be a scientific notation, in this case, parseInt will produce a wrong result.
在某些情况下,数字的字符串表示可以是科学记数法,在这种情况下, parseInt 会产生错误的结果。
parseInt(100000000000000000000000000000000, 10) // 1e+32
This call will produce 1 as result.
此调用将产生 1 作为结果。
回答by Cyberknight
JavaScript calculates right the floor of negative numbers and the remainder of non-integer numbers, following the mathematical definitions for them.
JavaScript 正确计算负数的下限和非整数的余数,遵循它们的数学定义。
FLOOR is defined as "the largest integer number smaller than the parameter", thus:
FLOOR 被定义为“小于参数的最大整数”,因此:
- positive numbers: FLOOR(X)=integer part of X;
- negative numbers: FLOOR(X)=integer part of X minus 1 (because it must be SMALLER than the parameter, i.e., more negative!)
- 正数:FLOOR(X)=X 的整数部分;
- 负数:FLOOR(X)=X 的整数部分减 1(因为它必须比参数更小,即更负!)
REMAINDER is defined as the "left over" of a division (Euclidean arithmetic). When the dividend is not an integer, the quotient is usually also not an integer, i.e., there is no remainder, but if the quotient is forced to be an integer (and that's what happens when someone tries to get the remainder or modulus of a floating-point number), there will be a non-integer "left over", obviously.
REMAINDER 定义为除法的“剩余部分”(欧几里德算术)。当被除数不是整数时,商通常也不是整数,即没有余数,但如果商被强制为整数(这就是当有人试图获得余数或模数时发生的情况)浮点数),显然会有一个非整数“遗留”。
JavaScript does calculate everything as expected, so the programmer must be careful to ask the proper questions (and people should be careful to answer what is asked!) Yarin's first question was NOT "what is the integer division of X by Y", but, instead, "the WHOLE number of times a given integer GOES INTO another". For positive numbers, the answer is the same for both, but not for negative numbers, because the integer division (dividend by divisor) will be -1 smaller than the times a number (divisor) "goes into" another (dividend). In other words, FLOOR will return the correct answer for an integer division of a negative number, but Yarin didn't ask that!
JavaScript 确实按预期计算了所有内容,因此程序员必须小心地提出正确的问题(人们应该小心地回答所问的问题!)Yarin 的第一个问题不是“X 除以 Y 的整数除法是什么”,但是,相反,“给定整数进入另一个的整个次数”。对于正数,两者的答案相同,但对于负数则不同,因为整数除法(除以除数)将比一个数(除数)“进入”另一个(除数)的时间小 -1。换句话说,FLOOR 将返回负数的整数除法的正确答案,但 Yarin 没有问这个问题!
gammax answered correctly, that code works as asked by Yarin. On the other hand, Samuel is wrong, he didn't do the maths, I guess, or he would have seen that it does work (also, he didn't say what was the divisor of his example, but I hope it was 3):
gammax 回答正确,该代码按 Yarin 的要求工作。另一方面,塞缪尔错了,他没有做数学,我猜,否则他会看到它确实有效(而且,他没有说他的例子的除数是多少,但我希望它是3):
Remainder = X % Y = -100 % 3 = -1
余数 = X % Y = -100 % 3 = -1
GoesInto = (X - Remainder) / Y = (-100 - -1) / 3 = -99 / 3 = -33
进入 = (X - 余数) / Y = (-100 - -1) / 3 = -99 / 3 = -33
By the way, I tested the code on Firefox 27.0.1, it worked as expected, with positive and negative numbers and also with non-integer values, both for dividend and divisor. Example:
顺便说一下,我在 Firefox 27.0.1 上测试了代码,它按预期工作,有正数和负数,也有非整数值,无论是被除数还是除数。例子:
-100.34 / 3.57: GoesInto = -28, Remainder = -0.3800000000000079
-100.34 / 3.57:进入 = -28,余数 = -0.3800000000000079
Yes, I noticed, there is a precision problem there, but I didn't had time to check it (I don't know if it's a problem with Firefox, Windows 7 or with my CPU's FPU). For Yarin's question, though, which only involves integers, the gammax's code works perfectly.
是的,我注意到,那里有一个精度问题,但我没有时间检查它(我不知道是 Firefox、Windows 7 还是我的 CPU 的 FPU 有问题)。然而,对于 Yarin 的问题,它只涉及整数,gammax 的代码运行良好。
回答by Aetricity
Math.floor(operation)
returns the rounded down value of the operation.
Math.floor(operation)
返回操作的向下舍入值。
Example of 1stquestion:
第一个问题示例:
var x = 5;
var y = 10.4;
var z = Math.floor(x + y);
console.log(z);
Console:
安慰:
15
15
Example of 2ndquestion:
第二个问题的例子:
var x = 14;
var y = 5;
var z = Math.floor(x%y);
console.log(x);
Console:
安慰:
4
4
回答by user1920925
Calculating number of pages may be done in one step: Math.ceil(x/y)
计算页数可以一步完成:Math.ceil(x/y)