javascript 50 到 80 之间的数学随机数

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

Math random numbers between 50 and 80

javascriptjquery

提问by John the Painter

I know there's several questions on this, but I'm struggling to find out how to use Math.random to get random numbers between two high integers?

我知道这有几个问题,但我正在努力找出如何使用 Math.random 在两个高整数之间获取随机数?

So, for example, between 50 and 80. I thought this would work...

所以,例如,在 50 到 80 之间。我认为这会起作用......

'left': Math.floor((Math.random() * 80) + 50) + '%'

Any ideas?

有任何想法吗?

回答by kayz1

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

回答by Karl-André Gagnon

You need to know the range of the random.

你需要知道随机的范围。

Between 50 and 80, the range is 30 (80 - 50 = 30), then you add 1.

在 50 和 80 之间,范围是 30 (80 - 50 = 30),然后加 1。

Therefor, the random would look like this :

因此,随机看起来像这样:

Math.floor(Math.random() * 31) + 50