JS生成随机数,生成指定位数的随机数

<html>
<script>
  //获取指定位数的随机数
  function getRandom(num) {
    let random = Math.floor((Math.random() + Math.floor(Math.random() * 9 + 1)) * Math.pow(10, num - 1));
  }
  //调用随机数函数生成10位数的随机数
  getRandom(10);
</script>
</html>

实现思路,以获取10位随机数为例:

Math.random()函数可以获得0到1之间的小数

Math.pow(10,10)函数进行幂运算等价于10的10次方

Math.floor()函数向下取整去除小数位

 组合起来则可以获得一个10位的随机数:

Math.floor(Math.random()*Math.pow(10,10))

将Math.randow()加1,排除第一位小数位为0的情况,相应的幂运算减一位

Math.floor((Math.random()+1))*Math.pow(10,9))

如此将获得一个10位的随机数,但是都将以1开头 

为了开头也能随机取数,可以将1替换为:

Math.floor(Math.random()*9+1)

最终的代码如下所示:

Math.floor((Math.random()+Math.floor(Math.random()*9+1))*Math.pow(10,9))

如此就可以获得一个完全随机的10位随机数了

 代码解析及执行结果:

//获取随机数,小数第一位可能为0
console.log(Math.random());

//获取10位随机数,如果小数第一位为0则只有9位数
console.log(Math.floor(Math.random() * Math.pow(10, 10)));

//随机数+1,解决小数第一位为0的情况
//但是会导致随机数的第一位总是为1
console.log(Math.floor((Math.random() + 1) * Math.pow(10, 9)));

//将随机数+1也改为随机加上1~9之间的数字,解决第一位总是为1的问题
console.log(
  Math.floor(
    (Math.random() + Math.floor(Math.random() * 9 + 1)) * Math.pow(10, 9)
  )
);

/*  Chrome浏览器调试运行结果-----------------------------------------------------------------------------
        获取随机数,小数第一位可能为0:
        0.097574709201919
        获取10位随机数,如果小数第一位为0则只有9位数:
        623721160
        随机数 + 1,解决小数第一位为0的情况:
        但是会导致随机数的第一位总是为1:
        1242782126
        将随机数 + 1也改为随机加上1~9之间的数字,解决第一位总是为1的问题:
        7671051679 */

猜你喜欢

转载自blog.csdn.net/weixin_43743175/article/details/129274932