生成范围内不以零开始的随机整数

Generating random integer in range that doesn't start at zero

本文关键字:开始 随机 整数 范围内      更新时间:2023-09-26

如何生成7到10之间的数字?到目前为止,我所知道的是在0-10的范围内生成:

Math.floor(Math.random()*11)
function getRandom(min, max) {
    return min + Math.floor(Math.random() * (max - min + 1));
}
for(var x = 0; x < 5; x++) {
    console.log(getRandom(7, 10));
}

Math.floor(7 + Math.random() * 4)将生成从7到10的数字

就这么说:

Math.floor(Math.random()*4) + 7

这将生成一个0-3的随机数,然后加上7,得到7-10。

7 + Math.floor(Math.random()*4)