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;
}
本文来自博客园,作者:重庆熊猫,转载请注明原文链接:https://www.cnblogs.com/cqpanda/p/16550737.html