理解随机数 Math.floor(Math.random() * (max - min + 1) + min)

理解随机数 Math.floor(Math.random() * (max - min + 1) + min)


前言

众所周知 Math.floor(Math.random() * (max - min + 1) + min) ,会得到 [min,max]之间的随机整数


一、那么怎么得到一个随机数?

大家都知道 Math.random()方法 会得到0~1 之间随机的小数

但是那怎么得到 2~99 之间的随机数呢?
在这里插入图片描述
随机数就是: 最小值 + 扩大区间

min + Math.random() * (max - min)
于是我们得到了(2~99)之间的随机小数

下面我们只需要把 小数转化成 整数就大功告成了!

二、尝试

1.使用Math.round()四舍五入小数

Math.round(Math.random() * (max - min)+min)

function number(min,max){
return Math.round(Math.random() * (max - min)+min)
};
console.log(number(2,99))
VM495:4 64

看起来我们成功得到了 随机数 但是好像跟 标题的Math.floor(Math.random() * (max - min + 1) + min)函数不一样

失败:
实际上获得的数并不随机,由于Math.round()四舍五入
(2~2.5) 才是2,而 [2.5~3.5) 是3,很明显这对2和99都不公平 ,它两的随机概率只有其他人的一半


三、使用Math.floor?

在js中 小数转整数 ,我们还有Math.floor() 向下取整 例: Math.floor(2.8)==2

我们上面得到了(min,max)之间的随机小数 :min + Math.random() * (max - min)

floor的问题是 ,
floor是向下取整!
floor是向下取整!
floor是向下取整!
使用floor 上面的随机小数是取不到 最大值的
那么 (min,max+1) , 扩大区间 +1就好了
Math.floor(Math.random() * (max - min ) + min) 取不到最大值 max
所以最终答案:
Math.floor(Math.random() * (max - min + 1) + min)


版权声明:本文为qq_44646982原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。