zoukankan      html  css  js  c++  java
  • Math

    在指定范围内,生成随机整数
     
    公式:
        Math.floor(Math.random * delta + minNum); // 返回 minNum ~ maxNum (maxNum = minNum + delta -1) 之间的正整数 -- 包含两侧边界值
        关键点是 delta的正确设置
      比如 :
        Math.floor(Math.random() * 10 + 1 ) -- 返回 1~10 之间的整数(包含1和10)
        Math.floor(Math.random() * 9 + 2 )  -- 返回 2~10 之间的整数(包含2和10)
     
    利用这个特性,可以提供一个公共函数:
      function genRandom(min,max){
        let delta = Math.abs(max - min + 1);
        return Math.floor(Math.random() * delta + min);
      }
     
    以下是验证代码 : set用于去重.
    var set = new Set();
    for(var i = 0 ; i< 1000 ; i++){
      set.put(Math.floor(Math.random() * 9 + 2 ));
    }
    console.log(set); // display 2 ~ 10 
     
  • 相关阅读:
    json_encode([0])
    try catch throw
    如何 lookback
    协程||进程
    客户错了?
    循环 php 变量会影响到传入的参数
    csv变成xls, csv乱码
    虚拟机不能git push
    数组下标大小写
    php 静态方法
  • 原文地址:https://www.cnblogs.com/lmxxlm-123/p/11131896.html
Copyright © 2011-2022 走看看