zoukankan      html  css  js  c++  java
  • random详解

    1、nextInt()用法:

    会随机生成一个整数,这个整数的范围就是int类型的范围-2^31 ~ 2^31-1,但是如果在nextInt()括号中加入一个整数a那么,这个随机生成的随机数范围就变成[0,a)。

    2、在题目给定数组时如何运用nextInt():

    上面提出的有趣题目是给定我们一个数组并且用来存放密码的组成元素,在这种给定我们已知的密码组成范围以及用数组来包括并且非同一组成的连续数据时,我们可以借鉴上面的问题答案代码

    for(int i=1 ; i<=6;i++)//六位数密码所以循环输出六次

    {

    int n =random.nextInt(62);//随机生成一个整数,这个整数的范围就是[0,62)

    System.out.print(pardStore[n]);//每次生成的整数n用pardStore[n]来代表一个数组中的数据

    }

    1、Random类
    Random random = new Random();
    random.nextInt();
    random.nextInt(1000)
    想生成1到1000的随机数
    int number = random.nextInt(1000+1-1)+1;
    int number = random.nextInt(最大值+1-最小值)+最小值;
    在使用的时候,需要导入java.util.Random包
    2、Math类
    Math类是java.lang包下的数学工具类,所以系统为自动导入,无须显示的导入
    Math.random();会返回一个大于等于0并且小于1的正小数
    想生成1到1000的随机数
    int number = (int)(Math.random()*(1000+1-1)+1);
    int number = (int)(Math.random()*(最大值+1-最小值)+最小值);


    补充:Random类可以设置随机种子,而Math类无须设置种子

  • 相关阅读:
    LeetCode 152. 乘积最大子数组 | Python
    LeetCode 31. 下一个排列 | Python
    LeetCode 136. 只出现一次的数字 | Python
    LeetCode 102. 二叉树的层序遍历 | Python
    LeetCode 155. 最小栈 | Python
    LeetCode 69. x 的平方根 | Python
    Python3 高阶函数
    Python3 装饰器
    Python3 递归函数
    Python3 函数
  • 原文地址:https://www.cnblogs.com/birdterror/p/12711776.html
Copyright © 2011-2022 走看看