zoukankan      html  css  js  c++  java
  • Java学习之生成随机数

    1.Java中的方法random()可用于生成随机数,称为伪随机数生成器,它返回一个大于等于0.0、小于1.0的数(double类型),即0.0<=X<1.0 。之所以产生的数称为伪随机数,是因为它并不是真正随机的。当我们重复调用这个方法时,最终生成的数是周期性重复的。因此,理论上,生成的数不随机,但对于实际应用说,它们已经足够随机了。

    但对于大多数应用程序来说,我们希望生成的随机数是整数。因此我们需要对于这个返回的数值进行转换,期望它落在我们需要的区间内。不妨假设我们需要的整数范围是[min, max],如果X是返回的随机数,可以使用下面的公式使其转换成Y,使得Y落在区间[min, max]内,即min<=Y<=max。

    Y = [X * (max-min+1)] + min

    对于很多应用程序来说,min的值是1,所以上式可简化为:

    Y = (X * max) + 1

    可以用下面的语句表达上面的通用公式:

    int randomNumber = (int) (Math.floor(Math.random() * (max - min + 1)) + min);

    实例(1):我们来编写一个小程序,要选出一个每年一届的春季交谊舞联欢会的中奖者,联欢会的参加者将会得到诸如M+1、M+2、M+3之类的数字进入场地。数字M的开始值由联欢会的主席确定,如果有N个选手参加,最后一个数字就是M+N。晚会的最后,我们将运行这个程序,从M+1到M+N中随机选择一个中奖者:

     1 import java.util.*;
     2 
     3 class Random_test{
     4     public static void main(String[] args){
     5         int startingNumber, count, winningNumber, min, max;
     6         
     7         Scanner scan = new Scanner(System.in);
     8         
     9         System.out.print("Enter the starting number: ");
    10         startingNumber = scan.nextInt();
    11         
    12         System.out.print("Enter the number of party goers: ");
    13         count = scan.nextInt();
    14         
    15         min = startingNumber + 1;
    16         max = startingNumber + count;
    17         
    18         winningNumber = (int) (Math.floor(Math.random() * (max - min + 1)) + min);
    19         
    20         System.out.print("
    The Winning Number is " + winningNumber);
    21     }
    22 }

    运行程序结果符合预期:

    2.Java中的Random类生成随机数实例,用到Random类中的nextInt(int)方法。例如Random random = new Random() ,代码random.nextInt(100)表示生成0-100之间的随机整数,包括0但不包括100,下面例子随机获得5个[1,100]的值:

     1 import java.util.*;
     2 
     3 class Random_test{
     4     public static void main(String[] args){
     5         Random random = new Random();
     6         for(int i=0; i<5; i++) {
     7             System.out.print(random.nextInt(100) + 1 + "
    ");
     8         }
     9     }
    10 }

    运行结果符合预期:

    生成区间[34,67]随机数可表示:random.nextInt(34)+34

    可以总结为:

    int randomNumber = random.nextInt(max - min + 1) + min;
  • 相关阅读:
    Java高级之类结构的认识
    14.8.9 Clustered and Secondary Indexes
    14.8.4 Moving or Copying InnoDB Tables to Another Machine 移动或者拷贝 InnoDB 表到另外机器
    14.8.3 Physical Row Structure of InnoDB Tables InnoDB 表的物理行结构
    14.8.2 Role of the .frm File for InnoDB Tables InnoDB 表得到 .frm文件的作用
    14.8.1 Creating InnoDB Tables 创建InnoDB 表
    14.7.4 InnoDB File-Per-Table Tablespaces
    14.7.2 Changing the Number or Size of InnoDB Redo Log Files 改变InnoDB Redo Log Files的数量和大小
    14.7.1 Resizing the InnoDB System Tablespace InnoDB 系统表空间大小
    14.6.11 Configuring Optimizer Statistics for InnoDB 配置优化统计信息用于InnoDB
  • 原文地址:https://www.cnblogs.com/m-chen/p/9456726.html
Copyright © 2011-2022 走看看