JS获取随机数 Math.random()

    xiaoxiao2026-02-26  8

    Math.random()是令系统随机选取大于等于 0.0 且小于 1.0 的伪随机 double 值,是Java语言常用代码。

    例如:var a:Number=Math.random()*2+1,设置一个随机1到3的变量。


    Math.random():产生一个[0,1)之间的随机数。

    返回指定范围的随机数[m,n]的公式:Math.random()*(n-m+1)+m;

    例:

    生成一个6位的随机字符串:

    public static void main(String[] args){

    String result=”“;

    for(int i=0;i<6;i++){

    //生成97-122的int型的整型

    int intValue=(int)(Math.random()*26+97);

    //将intValue强制转化成char类型后接到resul后面

    result=result+(char)intValue;

    }

    //输出字符串

    System.out.println(result);

    }


    Math:数学对象,提供对数据的数学计算。 Math.random(); 返回0和1间(包括0,不包括1)的一个随机数。

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

    Math.round(n); 返回n四舍五入后整数的值。 用Math.round(Math.random());可均衡获取0到1的随机整数。 用Math.round(Math.random()*10);时,可基本均衡获取0到10的随机整数,其中获取最小值0和最大值10的几率少一半。

    Math.floor(n); 返回小于等于n的最大整数。 用Math.floor(Math.random()*10);时,可均衡获取0到9的随机整数。

    转载请注明原文地址: https://ju.6miu.com/read-1307412.html
    最新回复(0)