zoukankan      html  css  js  c++  java
  • JS生成指定位数的随机

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

    实现思路(文末有代码过程及运行结果),以获取10位随机数为例:

    1、Math.random()函数可以获得0到1之间的小数,Math.pow(10,10)函数进行幂运算等价于10的10次方,Math.floor()函数向下取整去除小数位;

    2、组合起来则可以获得一个10位的随机数:Math.floor(Math.random()*Math.pow(10,10));

    3、但是,如果Math.randow()的第一位小数位为0则可能获得的是9位随机数;

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

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

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

    5、为了开头也能随机取数,可以将1替换为Math.floor(Math.random()*9+1);

    6、最终的代码如下所示:

    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
  • 相关阅读:
    Spring MVC 核心组件详解
    Spring MVC 入门就这一篇
    Spring 事务解决方案
    【UGUI源码分析】Unity遮罩之Mask详细解读
    游戏开发中不同时区下的时间问题
    ARTS第十三周(阅读Tomcat源码)
    Win10 电脑安装.NET低版本提示“这台计算机中已经安装了 .NET Framwork 4.6.2或版本更高的更新”问题
    Dynamics 365 Setup 提示SqlServer 存在
    Dynamics CRM "Verification of prerequisites for Domain Controller promotion failed. Certificate Server is installed."
    Dynamics CRM
  • 原文地址:https://www.cnblogs.com/sunyucui/p/6804481.html
Copyright © 2011-2022 走看看