javascript生成指定范围随机数
作者:互联网
范围随机数生成(整数)
//min ≤ r ≤ max
function randomNumBoth(min,max){
var range = max - min;
var rand = Math.random();
var num = min + Math.round(rand * range); //四舍五入
return num;
}
//min ≤ r < max
function randomNum(min, max) {
var range = max - min;
var rand = Math.random();
var num = min + Math.floor(rand * range); //舍去
return num;
}
//min < r ≤ max
function randomNum(min, max) {
var range = max - min;
var rand = Math.random();
if(Math.round(rand * range)==0){
return min + 1;
}
var num = min + Math.round(rand * range);
return num;
}
//min < r < max
function randomNum(min, max) {
var range = max - min;
var rand = Math.random();
if(Math.round(rand * range)==0){
return min + 1;
}else if(Math.round(rand * max)==max)
{
index++;
return max - 1;
}else{
var num = min + Math.round(rand * range) - 1;
return num;
}
}
范围随机数生成(非整数)
//取得[n,m]范围随机数
function fullClose(n,m) {
var result = Math.random()*(m+1-n)+n;
while(result>m) {
result = Math.random()*(m+1-n)+n;
}
return result;
}
//取得(n,m)范围随机数
function fullOpen(n,m) {
var result = Math.random()*(m-n)+n;
while(result == n) {
result = Math.random()*(m-n)+n;
}
return result;
}
//取得(n,m]范围随机数
function leftOpen(n,m) {
var result = Math.random()*(m-n+1)+n-1;
while(result<n) {
result = Math.random()*(m-n+1)+n-1;
}
return result;
}
标签:rand,min,max,javascript,指定,result,随机数,var,Math 来源: https://www.cnblogs.com/cqpanda/p/16550737.html