js 随机数
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title></title> 6 <meta charset="utf-8" /> 7 <script> 8 //取值范围min-max; 9 //能随机到min和max[min,max] 10 function rnd(min, max) { 11 var tmp = min; 12 if (max < min) { min = max; max = tmp; }//交换值 13 return Math.floor(Math.random() * (max - min + 1) + min); //向下取整 14 } 15 for (i = 0; i < 10; i++) { 16 document.write(rnd(5, 7)+"<br/>"); 17 } 18 19 </script> 20 <script> 21 //取值范围min-max; 22 //能随机到min 不能随机到max [min,max) 23 function rnd(min, max) { 24 var tmp = min; 25 if (max < min) { min = max; max = tmp; }//交换值 26 return Math.floor(Math.random() * (max - min) + min); //向下取整 27 } 28 for (i = 0; i < 10; i++) { 29 document.write(rnd(1,5) + "<br/>"); 30 } 31 </script> 32 <script> 33 //取值范围min-max; 34 //能随机到max 不能随机到min (min,max] 35 function rnd(min, max) { 36 var tmp = min; 37 if (max < min) { min = max; max = tmp; }//交换值 38 return Math.ceil(Math.random() * (max - min) + min); //向上取整 39 } 40 for (i = 0; i < 10; i++) { 41 document.write(rnd(1, 5) + "<br/>"); 42 } 43 </script> 44 45 <script> 46 //取值范围min-max; 47 //不能随机到min和max(min,max) 48 function rnd(min, max) { 49 var tmp = min; 50 var temp; 51 if (max < min) { min = max; max = tmp; }//交换值 52 temp = Math.floor(Math.random() * (max - min + 1) + min); //向下取整 53 if (min == temp) { 54 return min + 1; 55 } else { 56 return temp; 57 } 58 } 59 </script> 60 <!-- 61 var a = max/min; a = 7; 62 var xs = (a - 1); xs = 7/1 - 1 = 6; 63 var x=(max-1.0001)/min-1 x ((7-1.0001)/1)-1 = 5.9995; x/xs = 5.9995/6 = 0.99991 64 (7 - 1) * (0.999 *(x/xs))) = 6.9999 向上取整 ==6 65 1 + 6 * (0.1 *(x/xs)) = 1.09991 向上取整 ==2 66 原理是 最小数 + 最小数{(a-1)(随机数)(缩小比例x/xs)} 67 1(1+6)(0.999*0.9999) = 68 当min=1时候; a= max; 69 --> 70 <script> 71 function rnd(min,max){ 72 var a = max / min; 73 var xs = (a - 1); 74 var x = (max - 1.0001) / min - 1; 75 return Math.ceil(min * (1 + (a - 1) * (Math.random() *(x/xs)))); 76 } 77 for (i = 0; i < 100; i++) { 78 document.write("xxx开区间" + rnd(1,7) + "<br/>"); 79 } 80 81 </script> 82 <script> 83 function rnd() { 84 85 return parseInt(Math.random()*5); //取整 随机最大取5; 取值范围 5*(99%到0%)的数 (同上类似) 86 } 87 for (i = 0; i < 10; i++) { 88 document.write(rnd() + "<br />"); 89 } 90 </script></head> 91 <body> 92 93 </body> 94 </html>