随机数的获取

Math.ceil();  //向上取整。

Math.floor(); //向下取整。

Math.round(); //四舍五入。

Math.random(); //0.0 ~ 1.0 之间的一个伪随机数。【包含0不包含1】 //比如0.8647578968666494

Math.ceil(Math.random()*10); // 获取从1到10的随机整数 ,取0的概率极小。

Math.round(Math.random()); //可均衡获取0到1的随机整数。

Math.floor(Math.random()*10); //可均衡获取0到9的随机整数。

Math.round(Math.random()*10); //基本均衡获取0到10的随机整数,其中获取最小值0和最大值10的几率少一半。
因为结果在 0~0.4 为 0,0.5 到 1.4 为 1,8.5 到 9.4 为 9,9.5 到 9.9 为 10。所以头尾的分布区间只有其他数字的一半。

获取一个随机数:
function getRandom() {
return Math.round(Math.random()*10)
}
console.log(getRandom())

获取两个数之间的随机数:
function getRandom(min,max) {
return Math.random()*(max-min)+min;
}
console.log(getRandom(1,5))

获取两个数之间的随机整数(含最小值不含最大值):
function getRandomInt(min,max) {
min=Math.ceil(min) //向上取整
max=Math.floor(max)//向下取整
return Math.floor(Math.random()*(max-min)) +min//含最大值,不含最小值
}
console.log(getRandomInt(1,5))
 
获取两个数之间的随机整数(含最小值也含最大值):
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值
}
console.log(getRandomIntInclusive(1,5));
 
 

猜你喜欢

转载自www.cnblogs.com/hy96/p/11374006.html