简体   繁体   English

JavaScript - 找出一个数字均匀分配到另一个数字的次数

[英]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.

相关问题 如何将一个数尽可能多地除以2,然后在Javascript中打印出来? - How to divide a number by 2 as many times as possible, and then print it out in Javascript? 如何在 Javascript 中尽可能多地将一个数除以 2? - How to divide a number by 2 as many times as possible in Javascript? 如何生成一个可以被另一个随机生成的数整除的随机数 - How to generate a random number that is evenly divisible by another randomly generated number 有没有办法在javascript中找出某个字符串在数组中的次数? - Is there a way in javascript to find out how many times a certain string is in an array? Javascript:编写一个接受数字的函数,并多次返回带有该数字的数组 - Javascript: Write a function that takes in a number, and returns an array with that number in it that many times 如何使用 JavaScript 找到出现次数最多的数字? - How can I find the number that occurs most number of times using JavaScript? 在Javascript中,如何找到并解析出6位数字? - In Javascript, how can I find and parse out a 6 digit number? 如何找出JavaScript阵列中的元素数量? - How do I find out the number of elements in a Javascript array? 如何使用JavaScript找出从xml检索的元素数量 - How to find out the number of elements retrieved from a xml using javascript javascript如果数字可以被整除,则为true;否则为true - javascript if number is evenly divisible true if not false
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM