javascript 在不从零开始的范围内生成随机整数

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

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

javascriptrandom

提问by Winthan Aung

How can I generate numbers between 7 to 10? So far all I've figured out is generating in a range from 0-10:

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

Math.floor(Math.random()*11)

回答by Jordan

function getRandom(min, max) {
    return min + Math.floor(Math.random() * (max - min + 1));
}

for(var x = 0; x < 5; x++) {
    alert(getRandom(7, 10));
}

回答by David Titarenco

Math.floor(7 + Math.random() * 4)will generate numbers from 7 to 10 inclusive.

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

回答by Justin Ethier

Just say this:

就这么说吧:

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

This will generate a random number from 0-3 and then add 7 to it, to get 7-10.

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

回答by Soony

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