How can I generate a random whole number between two specified variables in Javascript, e.g. x = 4
and y = 8
would output any of 4, 5, 6, 7, 8?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Do the Java Integer and Double objects have unnece
- Keeping track of variable instances
this is my take on a random number in a range, as in I wanted to get a random number within a range of base to exponent. e.g. base = 10, exponent = 2, gives a random number from 0 to 100, ideally, and so on.
if it helps use it, here it is:
To get a random number say between 1 and 6, first do:
This multiplies a random number by 6 and then adds 0.5 to it. Next round the number to a positive integer by doing:
This round the number to the nearest whole number.
Or to make it more understandable do this:
In general the code for doing this using variables is:
The reason for taking away 0.5 from the minimum value is because using the minimum value alone would allow you to get an integer that was one more than your maximum value. By taking away 0.5 from the minimum value you are essentially preventing the maximum value from being rounded up.
Hope that helps.