调用类java.lang.Math成员方法“public static double random”运算下面表达式10000次
(int)(Math.random()*20+0.5)
统计其中生成的整数 0,1,2,...,20的个数分别为多少,并输出统计结果!
1 public class HomeWork4 { 2 public static void main(String[] args) 3 { 4 int sum = 0; 5 int[] arr=new int[20]; 6 for(int i = 0; i<10000;i++) 7 { 8 int a = (int)(Math.random()*20+0.5); 9 for(int j=0; j<20; j++ ) 10 { 11 if(a==j+1) 12 arr[j]=arr[j]+1; 13 } 14 } 15 for(int k = 0; k<20;k++){ 16 System.out.println("数字"+ (k+1) +"总共有"+arr[k]+"个"); 17 } 18 } 19 }
巧妙利用 数组进行统计 不用写那么多判断了