[英]JavaScript - Find out how many times a number goes into another number evenly
Is there a simple way to find how many times a number goes into another number evenly in JavaScript? 有没有一种简单的方法可以找到一个数字在JavaScript中均匀分配到另一个数字的次数?
Say 11 divided by 4 --- I know 4 goes into 11 2 times evenly 说11除以4 ---我知道4次均匀地进入11次2次
I have this code but I thought there was a simpler way that I maybe forgetting? 我有这个代码,但我认为有一种更简单的方法,我可能会忘记?
<script>
a = 11;
b = 4;
i = a % b;
i2 = a - i;
solution = i2 / b;
document.write(solution); // 2
</script>
What about... 关于什么...
Math.floor(11 / 4);
If you're wanting to handle negative numbers (thanks Ted Hopp ), you could use ~~
, |0
or any other bitwise trick that will treat its operand as a 32 bit signed integer. 如果你想处理负数(感谢Ted Hopp ),你可以使用
~~
, |0
或任何其他按位技巧将其操作数视为32位有符号整数。 Keep in mind, besides this being confusing, it won't handle a number over 32bits. 请记住,除了令人困惑之外,它不会处理超过32位的数字。
~~(11 / 4);
You can use this trick: 你可以使用这个技巧:
(a / b) >> 0
Shifting by 0 truncates the fractional part. 按0移位会截断小数部分。 This will always round toward 0, which
Math.floor
will not do with negative numbers. 这将始终向0舍入,
Math.floor
不会对负数进行舍入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.