js产生随机数


 1  < script >
 2 document.write(parseInt(10*Math.random()));   // 输出0~10之间的随机整数
 3 
 4 document.write(Math.floor(Math.random()*10+1));   // 输出1~10之间的随机整数
 5 
 6  function RndNum(n){
 7  var rnd="";
 8  for( var i=0;i<n;i++)
 9 rnd+=Math.floor(Math.random()*10);
10  return rnd;
11 }
12 document.write(RndNum(4));   // 输出指定位数的随机数的随机整数
13 
14 
15 
16 引用部分: 
17 
18 1. 从1开始 至 任意值
19 parseInt(Math.random()*上限+1); 
20 
21 2. 从任意值开始 至 任意值
22 parseInt(Math.random()*(上限-下限+1)+下限); 
23  function fRandomBy(under, over){ 
24  switch(arguments.length){ 
25  case 1:  return parseInt(Math.random()*under+1); 
26  case 2:  return parseInt(Math.random()*(over-under+1) + under); 
27  defaultreturn 0; 
28 } 
29 } 
30 document.write(fRandomBy(1,100));   // 输出指定范围内的随机数的随机整数
31  </ script >
32 
33 //给既定文本框按规则付不同的值[引申]
34  < script >
35 window.onload= function(){ 
36  var o=document.getElementsByTagName('input'); 
37 o[0].value=fRandomBy(1,10); 
38 o[1].value=fRandomBy(11,20); 
39 o[2].value=fRandomBy(1,100); 
40 o[3].value=fRandomBy(51,100); 
41 }
42  </ script >
43 1-10:  < input  type ="text"   />< br  /> 
44 11-20:  < input  type ="text"   />< br  /> 
45 1-100:  < input  type ="text"   />< br  /> 
46 51-100:  < input  type ="text"   />< br  /> 
47  
48 
49  
50 
51  < html >
52  < head >
53  < title >Math </ title >
54  </ head >
55  < body >
56  < script  language ="javascript"  type ="text/javascript" >
57 total = 0
58  for(i=1;i<=5000;i++)
59 {num=Math.random();
60 total +=num
61 }
62 average = total/5000
63 average = Math.round(average*1000)/1000
64 document.write("<h1>平均数:"+average+"</h1>")
65  </ script >
66  </ body >
67  </ html >


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM