范围随机数生成(整数)
//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;
}
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/279825.html