zoukankan      html  css  js  c++  java
  • javascript生成n至m的随机整数

    摘要:

      本文讲解如何使用js生成n到m间的随机数字,主要目的是为后期的js生成验证码做准备。

      Math.random()函数返回0和1之间的伪随机数,可能为0,但总是小于1,[0,1)

    生成n-m,包含n但不包含m的整数:

    第一步算出 m-n的值,假设等于w

    第二步Math.random()*w

    第三步Math.random()*w+n

    第四步parseInt(Math.random()*w+n, 10)

    生成n-m,不包含n但包含m的整数:​

    第一步算出 m-n的值,假设等于w

    第二步Math.random()*w

    第三步Math.random()*w+n

    第四步Math.floor(Math.random()*w+n) + 1

    生成n-m,不包含n和m的整数:

    第一步算出 m-n-2的值,假设等于w

    第二步Math.random()*w

    第三步Math.random()*w+n +1

    第四步Math.round(Math.random()*w+n+1) 或者 Math.ceil(Math.random()*w+n+1)

    生成n-m,包含n和m的随机数:

    第一步算出 m-n的值,假设等于w

    第二步Math.random()*w

    第三步Math.random()*w+n

    第四步Math.round(Math.random()*w+n) 或者 Math.ceil(Math.random()*w+n)

    例子:

      生成800-1500的随机整数,包含800但不包含1500

    1. 1500-800 = 700
    2. Math.random()*700
    3. var num = Math.random()*700 + 800;
    4. num = parseInt(num, 10);

    只需要简单的四步就可以完成。

    补充:

      Math.ceil()      返回大于等于数字参数的最小整数(取整函数),对数字进行上舍入

      Math.floor()    返回小于等于数字参数的最大整数,对数字进行下舍入

      Math.round()  返回数字最接近的整数,四舍五入

  • 相关阅读:
    flex 和bison的安装和使用
    c++ map
    C++ 值传递、址传递、引用传递
    位运算
    POJ 1185 炮兵阵地 (状压DP)
    POJ 3114 Countries in War(强联通分量+Tarjan)
    Codeforces Round #262 (Div. 2) A B C
    2014多校第十场1002 || HDU 4972 A simple dynamic programming problem
    2014多校第十场1004 || HDU 4974 A simple water problem
    POJ 1144 Network(Tarjan)
  • 原文地址:https://www.cnblogs.com/115FXC/p/4012573.html
Copyright © 2011-2022 走看看