随机数函数
https://www.bilibili.com/video/BV1W54y1J7Ed?p=26
简码 Math.floor(Math.random()*(max-min+1))+min
源码:
// 取到min到max(不含)之间的随机数
function getRandom(min,max){
// 因为用Math.floor()向下取整,所以((max - min) + 1)
let initNum = Math.random() * ((max - min) + 1);
let finNum = Math.floor(initNum + min);
// console.log(finNum);
return finNum;
}
思路:
- 获取 x ~ y 之间的随机整数!!!
- 则先取 0 ~ 两数差 之间的随机数,然后 + 小一点得数字
- Math.random() 获取一个 0 ~ 0.999… 的随机小数
- 将这个数乘于
⭐拓展
注意 Math.round() Math.ceil() Math.floor() 的三种取整值得方法使用!!!!!
会导致取得的数值 0 - 10 概率不同
eg
1. 使用 Math.round()时,每个值取到概率不一样
-
取0 - 10 随机数
-
// for(i=0;i<100;i++){ let num = Math.random() * 10; let finNum = Math.round(num); console.log(finNum); // } // num = 0 ~ 0.4999时 ,finNum 取 0 // num = 0.5 ~ 1.499时,finNum 取 1 // 以此类推 // num = 8.5 ~ 9.499时,finNum 取 9 // num = 9.5 ~ 9.999时,finNum 取 10 // 从而 取0 与 10 的情况将比 取1-9的情况概率要小!!!!!
2. 使用 Math.ceil()时,需保持 - 0.99 ~ 0
才能取 0
不好操作
3. 使用 Math.floor()时,需在10 ~ 10.999
才能取10
可行 !!!!!!且每个值概率相同!!
(仅需 在运算时最大值+1 即可—(因为只取0-0.999)即便加1 也无法取最大值+1的整数)
取0 - 10 随机数
for(i=0;i<100;i++){
// 注意乘以 11 ,
// 0.9*11 = 9.9,Math.floor(9.9) = 9!
// 0.91*11 = 10.01,Math.floor(10.01) = 10!
let num = Math.random() * 11;
let finNum = Math.floor(num);
console.log(finNum);
}
拓展
JS 实际例子工具 https://c.runoob.com/examples/