Javascript 随机数 int 范围一个数 float

1.随机取int范围一个数,比如0-3中取0,1,2,3,同时包含0和3

<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>

因为javascirpt的Math.random()的范围是[0,1),包含0,不包含1,错误写法中,因为Math.floor是向下取整,所以:

Math.floor([0,1) * 3) + 0 的取值范围是[0,1,2],永远取不到3.

 

2.随机取float范围一个数

<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

1760

Leave a Reply

Name and Email Address are required fields.
Your email will not be published or shared with third parties.