zoukankan      html  css  js  c++  java
  • js 随机数

    js生成随机数有以下几种方式

    1、JavaScript Math.random()内置函数

    random函数返回值

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

    random函数示例

     //返回随机数

    document.write(Math.random());

    //返回10-20的随机数

    document.write(Math.random()*(20-10)+10);

    //返回指定范围的随机数(m-n之间)的公式

    document.write(Math.random()*(n-m)+m);


    2、Math.ceil(n); 返回大于等于n的最小整数。


    用Math.ceil(Math.random()*10);时,主要获取1到10的随机整数,取0的几率极小。


    3、Math.round(n); 返回n四舍五入后整数的值。


    用Math.round(Math.random());可均衡获取0到1的随机整数。
    用Math.round(Math.random()*10);时,可基本均衡获取0到10的随机整数,其中获取最小值0和最大值10

    的几率少一半。


    4、Math.floor(n); 返回小于等于n的最大整数。


    用Math.floor(Math.random()*10);时,可均衡获取0到9的随机整数。

    5、基于时间,亦可以产生随机数

    var now=new Date();
    
    var number = now.getSeconds(); //这将产生一个基于目前时间的0到59的整数。
    
    var now=new Date();
    
    var number = now.getSeconds()%43; //这将产生一个基于目前时间的0到42的整数。
    
  • 相关阅读:
    自由工作者,从今天开始
    C#中MessageBox用法大全
    目前国内常见医用显示器品牌
    C#中可直接调用WIN32的API函数--USER32.DLL
    马年新年祝福
    PID算法学习记录
    Qt网络编程之使用cookie
    Qt使用HTTPS协议访问网站
    使用Qt访问网站的基本例子
    Qt TLS初始化失败解决办法
  • 原文地址:https://www.cnblogs.com/zonglonglong/p/4250467.html
Copyright © 2011-2022 走看看