在 2 个变量之间生成随机数 jquery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22363616/
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
generate random number between 2 variables jquery
提问by rpsep2
i need to generate a random number between -100 and a variable 'max_top' ( will always be a positive number, up to roughly 40). The number needs to be able to be a minus as well as positive.
我需要生成一个介于 -100 和变量“max_top”之间的随机数(将始终是正数,最多大约为 40)。该数字需要既可以是负值也可以是正值。
how can i do this?
我怎样才能做到这一点?
回答by Turnip
You dont need JQuery for this:
为此,您不需要 JQuery:
var minNumber = -100;
var maxNumber = 40
var randomNumber = randomNumberFromRange(minNumber, maxNumber);
function randomNumberFromRange(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}
console.log(randomNumber);
回答by Izaaz Yunus
You could use the Math.random() to generate the random number, multiply it to your range and add it to the lower bound.
您可以使用 Math.random() 生成随机数,将其乘以您的范围并将其添加到下限。
Something like this.
像这样的东西。
var min = -100;
var my_random_value = min + (max_top - min) * Math.random()
This will include a random number between -100 and max_top (both inclusive).
这将包括一个介于 -100 和 max_top(均包含在内)之间的随机数。
Math.random() - generates a random number between 0 and 1. When random is 0, my_random_value will be equal to min When random is 1, my_random_value will be equal to max_top
Math.random() - 生成一个介于 0 和 1 之间的随机数。当 random 为 0 时,my_random_value 将等于 min 当 random 为 1 时,my_random_value 将等于 max_top