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