zoukankan      html  css  js  c++  java
  • Math.random()详解

    Math.random()是令系统随机选取大于等于 0.0 且小于 1.0 的伪随机 double 值,是Java语言常用代码。例如:double a=Math.random()*(3-1)+1,设置一个随机1到3的变量。

    代码

    Math.random():产生一个[0,1)之间的随机数。
    返回指定范围的随机数(m-n之间)的公式 [1]  :
    1
    2
    Math.random()*(n-m)+m;
    改正公式:Math.random()*(n+1-m)+m
    例:
    生成一个6位的随机字符串:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    public static void main(String[]args){
    String result="";
    for(inti=0;i<6;i++){
    //生成97-122的int型的整型
    int intValue=(int)(Math.random()*26+97);
    //将intValue强制转化成char类型后接到result后面
    result=result+(char)intValue;
    }
    //输出字符串
    System.out.println(result);
    }

    使用方法

    例:用Math类的random()方法产生一个字符,若该字符是一个大写英文字母,则输入 "Yes!",否则输出“NO”。
    random()方法产生的随机数在0.0和1.0之间,乘以128后,其值在0.0和128.0之间,将它转换为char类型后,用if来判断是否在'A' 和'Z'之间。程序如下:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    classIsUpper{
    publicstaticvoidmain(String[]args){
    charch;
    ch=(char)(Math.random()*128);
    if(ch>='A'&&ch<='Z')
    System.out.println("Yes!");
    else
    System.out.println("No!");
    }
    }
    JavaScript Math.random() 函数
    Math.random() -- 返回0和1之间的伪随机数 可能为0,但总是小于1,[0,1)
    1
    document.write(Math.random());
    返回随机数
    1
    document.write(Math.random()*(20-10+1)+10);
    返回10-20的随机数
    1
    document.write(Math.random()*(n+1-m)+m);
    返回指定范围的随机数(m-n之间)的公式
  • 相关阅读:
    hadoop集群配置和测试
    ubuntu 12.04安装jdk
    springboot集成mybatis
    redis连接数据库
    生产随机数
    关于字符串统计次数
    闲的无聊写了一个房租的后台
    简单的死锁
    java集合类总结(转)
    mybatis框架的搭建
  • 原文地址:https://www.cnblogs.com/mark5/p/11201657.html
Copyright © 2011-2022 走看看