重庆熊猫 Loading

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;
}
posted @ 2022-08-11 08:02  重庆熊猫  阅读(147)  评论(0编辑  收藏  举报