有没有办法用JavaScript生成指定范围内的随机数?
例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。
有没有办法用JavaScript生成指定范围内的随机数?
例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。
当前回答
如果您想覆盖负数和正数,并确保其安全,请使用以下方法:
JS解决方案:
function generateRangom(low, up) {
const u = Math.max(low, up);
const l = Math.min(low, up);
const diff = u - l;
const r = Math.floor(Math.random() * (diff + 1)); //'+1' because Math.random() returns 0..0.99, it does not include 'diff' value, so we do +1, so 'diff + 1' won't be included, but just 'diff' value will be.
return l + r; //add the random number that was selected within distance between low and up to the lower limit.
}
Java解决方案:
public static int generateRandom(int low, int up) {
int l = Math.min(low, up);
int u = Math.max(low, up);
int diff = u - l;
int r = (int) Math.floor(Math.random() * (diff + 1)); // '+1' because Math.random() returns 0..0.99, it does not include 'diff' value, so we do +1, so 'diff + 1' won't be included, but just 'diff' value will be.
return l + r;//add the random number that was selected within distance between low and up to the lower limit.
}
其他回答
我在搜索用TypeScript编写的随机数生成器,在阅读了所有答案后,我写了这个,希望它对TypeScript程序员有用。
Rand(min: number, max: number): number {
return (Math.random() * (max - min + 1) | 0) + min;
}
尽管有许多答案,但结果几乎相同。我想补充一下我的答案并解释一下它的作用。因为理解它的工作方式比复制粘贴单行代码更重要。生成随机数只是简单的数学。
代码:
function getR(lower, upper) {
var percent = (Math.random() * 100);
// this will return number between 0-99 because Math.random returns decimal number from 0-0.9929292 something like that
//now you have a percentage, use it find out the number between your INTERVAL :upper-lower
var num = ((percent * (upper - lower) / 100));
//num will now have a number that falls in your INTERVAL simple maths
num += lower;
//add lower to make it fall in your INTERVAL
//but num is still in decimal
//use Math.floor>downward to its nearest integer you won't get upper value ever
//use Math.ceil>upward to its nearest integer upper value is possible
//Math.round>to its nearest integer 2.4>2 2.5>3 both lower and upper value possible
console.log(Math.floor(num), Math.ceil(num), Math.round(num));
}
范围[a,b]内的加密强随机整数(假设:a<b)
let rand=(a,b)=>a+(b-a+1)*crypto.getRandomValues(新Uint32Array(1))[0]/2**32|0console.log(兰特(1,6));
使用可重用的随机函数。
function randomNum(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
randomNum(1, 6);
或者,在Undercore
_.random(min, max)