标签:
<script> var rand = {}; rand.getInt = function (begin,end){ return Math.floor(Math.random()*(end-begin + 1)) + begin; } var v = rand.getInt(0,3) alert(v); </script>
常见错误写法:
<script> var rand = {}; rand.getInt = function (begin,end){ return Math.floor(Math.random()*(end-begin)) + begin; } var v = rand.getInt(0,3) alert(v); </script>
Math.floor([0,1) * 3) + 0 的取值范围是[0,1,2],永远取不到3.
<script> var rand = {}; rand.get = function (begin,end,precision){ return (Math.random()*(end-begin) + begin).toFixed(precision); } var v = rand.get(0,3,2) alert(v); </script>
这样取不到3,也是个问题,没有什么好办法吗?
http://www.waitingfy.com/archives/1760
版权声明:本文为博主原创文章,未经博主允许不得转载。
Javascript 随机数 int 范围一个数 float
标签:
原文地址:http://blog.csdn.net/fox64194167/article/details/48650187