zoukankan      html  css  js  c++  java
  • js随机生成

    math.random只是生成了一个伪随机数,之后还要经过处理才行。
     

    w3school的random()教程
    定义和用法

    random() 方法可返回介于 0 ~ 1 之间的一个随机数。
    语法

    Math.random()

    返回值

    0.0 ~ 1.0 之间的一个伪随机数。
    实例

    取 0 到 1 之间的一个随机数:

    <script type="text/javascript">
      document.write(Math.random());
    </script>
    // 输出:
    0.15246391076246546

    如何生成指定范围值的随机数

    利用 parseInt()、Math.floor() 或者 Math.ceil()进行四舍五入处理

      直接使用Math.random()方法,生成的是一个小于1的数,

    Math.random()*5
    得到的结果是一个小于5的随机数。而我们通常希望得到的是0-5之间的整数,结果通过四舍五入得到 整数。
    parseInt()、Math.floor()
    和 Math.ceil()都可以起到四舍五入的作用。
    var randomNum = Math.random()*5;
    alert(randomNum); // 2.9045290905811183 
    alert(parseInt(randomNum,10));  // 2
    alert(Math.floor(randomNum));   // 2
    alert(Math.ceil(randomNum));    // 3

      注:parseInt()Math.floor()的效果是一样的,都是向下取整数部分

        所以parseInt(Math.random()*5,10)Math.floor(Math.random()*5)都是生成的0-4之间的随机数
        Math.ceil(Math.random()*5)则是生成的1-5之间的随机数

    生成指定范围数值随机数

    所以,如果你希望生成1到任意值的随机数,公式就是这样的:

    // max - 期望的最大值
    parseInt(Math.random()*max,10)+1;
    Math.floor(Math.random()*max)+1;
    Math.ceil(Math.random()*max);

    如果生成0到任意值的随机数:

    // max - 期望的最大值
    parseInt(Math.random()*(max+1),10);
    Math.floor(Math.random()*(max+1));

    如果生成任意值到任意值的随机数:

    // max - 期望的最大值
    // min - 期望的最小值 
    parseInt(Math.random()*(max-min+1)+min,10);
    Math.floor(Math.random()*(max-min+1)+min);
  • 相关阅读:
    由于扩展配置问题而无法提供您请求的页面。如果该页面是脚本,请添加处理程序。
    中晟银泰国际中心酒店式公寓介绍 业主交流QQ群:319843248
    社保关系转移
    在中国,大数据的有效商业模式在哪里?
    指点传媒:在手机上做“精准营销”
    说说大型高并发高负载网站的系统架构【转】
    BI的相关问题[转]
    python 中有趣的库tqdm
    python之字符串操作方法
    比Screen更好用的神器:tmux
  • 原文地址:https://www.cnblogs.com/whoamimy/p/12588433.html
Copyright © 2011-2022 走看看