【Java】調用類java.lang.Math成員方法“public static double random”進行運算10000次,並統計


調用類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 }

巧妙利用 數組進行統計 不用寫那么多判斷了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM