标签:http io ar 使用 sp java div on cti
实现随机数是各种编程语言都很常见的一个编程任务,下面介绍一下在JavaScript如何实现随机数。第一中方法通过重写Math.random方法实现,第二种方法改自一个C实现,都可以实现编程目的。通榆县仲超农化
直接上代码:
01 |
<script language= "javascript" > |
02 |
var native_random = Math.random; |
03 |
Math.random = function (min, max, exact) { |
04 |
if (arguments.length === 0) |
05 |
{ |
06 |
return native_random(); |
07 |
} |
08 |
else if (arguments.length === 1) |
09 |
{ |
10 |
max = min; |
11 |
min = 0; |
12 |
} |
13 |
var range = min + (native_random()*(max - min)); |
14 |
return exact === void(0) ? Math.round(range) : range.toFixed(exact); |
15 |
}; |
16 |
document.write(Math.random()); |
17 |
document.write( ‘<br />‘ ); |
18 |
document.write(Math.random(10)); |
19 |
document.write( ‘<br />‘ ); |
20 |
document.write(Math.random(3,10)); |
21 |
document.write( ‘<br />‘ ); |
22 |
document.write(Math.random(2,10,4)); |
23 |
</script> |
程序运行结果如下:
1 |
0.2989420900121331 |
2 |
7 |
3 |
9 |
4 |
2.2469 |
如何不使用Math.random实现随机数呢?下面的函数改自一个C实现:
01 |
var random = ( function (){ |
02 |
var high = 1, low = 1 ^ 0x49616E42; |
03 |
var shuffle = function (seed){ |
04 |
high = seed; |
05 |
low = seed ^ 0x49616E42; |
06 |
} |
07 |
|
08 |
return function (){ |
09 |
var a = new Date()-0 |
10 |
shuffle(a); |
11 |
high = (high << 16) + (high >> 16); |
12 |
high += low; |
13 |
low += high; |
14 |
return high; |
15 |
} |
16 |
})(); |
17 |
|
18 |
p(random()); |
标签:http io ar 使用 sp java div on cti
原文地址:http://www.cnblogs.com/xiaoyang002/p/4101565.html