JavaScript - 找出一个数字平均进入另一个数字的次数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14494413/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:47:14  来源:igfitidea点击:

JavaScript - Find out how many times a number goes into another number evenly

javascript

提问by user1822824

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>

回答by alex

What about...

关于什么...

Math.floor(11 / 4);

If you're wanting to handle negative numbers (thanks Ted Hopp), you could use ~~, |0or any other bitwise trick that will treat its operand as a 32 bit signed integer. Keep in mind, besides this being confusing, it won't handle a number over 32bits.

如果您想处理负数(感谢Ted Hopp),您可以使用~~|0或任何其他将其操作数视为 32 位有符号整数的按位技巧。请记住,除了这令人困惑之外,它不会处理超过 32 位的数字。

~~(11 / 4);

回答by Ted Hopp

You can use this trick:

你可以使用这个技巧:

(a / b) >> 0

Shifting by 0 truncates the fractional part. This will always round toward 0, which Math.floorwill not do with negative numbers.

移动 0 会截断小数部分。这将始终向 0 舍入,这Math.floor与负数无关。