1》基础知识
Math.ceil():向上舍入
Marh.floor():向下舍入
Marh.round():四舍五入
console.log(Math.ceil(3.6));//4
console.log(Math.floor(3.6));//3
console.log(Math.round(3.6));//4
random()方法:(返回0-1包含0不包含1)
2》简单了解
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~0.4为0,0.5~1.4为1....9.5~9.9为10,所以头尾的分布区域只有其他数字的一半
3》生成随机数的情况分为4中,主要是边界问题
范围r在[min,max]
范围r在[min,max)
范围r在(min,max]
范围r在(min,max)
4》具体内容
生成[n,m]的随机数
function randomNum(minNum,maxNum){
switch(arguments.length){
case 1:
return Math.floor(Math.random()*minNum+1);
break;
case 2:
return Math.floor(Math.random()*(maxNum-minNum+1)+minNum);
break;
default:
return 0;
break;
}
}
Math.round(Math.random()*(maxNum-minNum)+minNum)
生成[n,m)的随机数
Math.floor(Math.random()*(maxNum-minNum)+minNum)
生成(n,m]的随机数
在Math.floor(Math.random()*(maxNum-minNum+1))为0的时候,返回最小值加1,其余为Math.floor(Math.random()*(maxNum-minNum+1)+minNum)
生成(n,m)的随机数
在Math.floor(Math.random()*(maxNum-minNum+1))为0的时候,返回最小值加1,在在Math.floor(Math.random()*(maxNum-minNum+1))为最大值的时候,返回最大值减一,其余Math.floor(Math.random()*(maxNum-minNum+1)+minNum)