随机数生成代码

随机数:
0<=Math.random()<1


(1)任意max和min之间取随机整数的公式:
var r=Math.floor(Math.random()*(max-min+1)+min)

(2)在0~max之间取随机整数:
var r=Math.floor(Math.random()*(max+1))

1. 取整:
(1)Math.ceil(num) 上取整: 只要超过,就取下一个整数

 


(2)Math.floor(num) 下取整: 只要超过,就抹掉小数部分

 

(3)Math.round(num) 四舍五入取整:

 

二、注意:

(1)Math.floor(num)  vs    parseInt(str)

floor: 参数是number,
不能去掉字符串结尾的非数字字符
parseInt: 参数是字符串,
专门去掉字符串结尾的非数字字符
缺: 强行去掉小数部分,会导致误差
解决: 首选parseFloat

 

(2)Math.round(num)   VS  toFixed(d)

round: 必须用Math直接调用
    缺: 只能取整
    优: 返回值: number 可直接算数计算
toFixed(d): 可被任意数字类型的值调用
    优: 可按任意小数位数四舍五入(0<=d<=20)
    缺: 返回值: string 先转为number再计算

(3)自定义round方法: 可按任意小数位数四舍五入
返回number

  

function round(num,d){
    //num* 10的d次方
  num*=Math.pow(10,d);
    //对num四舍五入取整
  num=Math.round(num);
    //num/ 10的d次方
  num/=Math.pow(10,d);
  return num;
}

 

应用,双色球摇号的代码

function doubleball(){
  var reds=[];//定义空数组reds
  //反复: 只要reds中少于6个
while(reds.length<6){
//在1~33之间生成一个随机整数r
var r=Math.floor(Math.random()*33+1);
//遍历reds中每个元素
for(var i=0;i<reds.length;i++){
//如果reds中当前元素等于r,就退出循环
if(reds[i]==r){break;}
}//(遍历结束)
//如果i等于reds的元素个数,就将r压入reds中
if(i==reds.length){reds.push(r);}
}//(循环结束)
//将reds按数字升序排列
reds.sort(function(a,b){return a-b});
//在1~16之间生成一个随机整数blue
var blue=Math.floor(Math.random()*16+1);
//返回 reds转为字符串 拼个| 拼上blue
return String(reds)+"|"+blue;
}
document.write("<h1>"+doubleball()+"</h1>");

posted @ 2016-12-01 17:35  木子青青  阅读(6511)  评论(0编辑  收藏  举报