经典问题-摇双色模拟(次数自定义)(Dice Rolling)

来源:互联网 发布:双11淘宝红包 编辑:程序博客网 时间:2024/06/09 19:15

调试了1个多小时,憋屎憋尿的,真不容易。大笑


代码如下:

package example;//Java how to program, 10th/e, Exercise 7.17-Dice Rolling/**(Dice Rolling) Write an application to simulate the rolling of two dice. The applicationshould use an object of class Random once to roll the first die and again to roll the second die. Thesum of the two values should then be calculated. Each die can show an integer value from 1 to 6, sothe sum of the values will vary from 2 to 12, with 7 being the most frequent sum, and 2 and 12 theleast frequent. Figure 7.28 shows the 36 possible combinations of the two dice. Your applicationshould roll the dice 36,000,000 times. Use a one-dimensional array to tally the number of timeseach possible sum appears. Display the results in tabular format.*/import java.util.Scanner;public class DiceRolling2016 {public static int rollDice(){   int dice1=(int)(1+Math.random()*6);   int dice2=(int)(1+Math.random()*6);   return dice1+dice2;   }public static void main(String[] args){int size=0;do{Scanner input=new Scanner(System.in);System.out.print("请输入摇双色的次数(输入-1退出):");size=input.nextInt();if(size==-1){System.out.printf("已退出程序");break;}int rollingResult=0;int[] frequency=new int[11];double[] possibility=new double[11];double possibilityTotal=0.0;double percentTotal=0.0;int totalRolling=0;System.out.println("摇双色开始:");for (int i=0;i<size;i++){   rollingResult=rollDice();   switch (rollingResult){   case 2:   frequency[0]++;   break;   case 3:   frequency[1]++;   break;   case 4:   frequency[2]++;   break;   case 5:   frequency[3]++;   break;   case 6:   frequency[4]++;   break;   case 7:   frequency[5]++;   break;   case 8:   frequency[6]++;   break;   case 9:   frequency[7]++;   break;   case 10:   frequency[8]++;   break;   case 11:   frequency[9]++;   break;   case 12:   frequency[10]++;   break;    }   }System.out.println("摇双色结束:");for (int i=0;i<11;i++){possibility[i]=(double)frequency[i]/size;}System.out.printf("已模拟摇双色共%d次,统计结果如下:\n",size);System.out.println("双色点数合计\t摇出次数\t\t所占百分比:");for (int i=0;i<11;i++){//百分比取两位小数推演过程:0.12545->1254.5+0.5=1255/10000=0.1255*100System.out.printf("%d\t\t%d\t\t%.2f",i+2,frequency[i],(double)(possibility[i]*10000+0.5)/100);System.out.print("%"+"\n");}for(double p:possibility){possibilityTotal+=p;percentTotal+=(p*10000+0.5)/100;}for(int f:frequency)totalRolling+=f;System.out.printf("校验值-摇出次数合计:%d,概率合计:%.2f,百分比合计:%.2f\n\n\n",totalRolling,possibilityTotal,percentTotal);}while(size!=-1);}}


运行结果:

请输入摇双色的次数(输入-1退出):10000000
摇双色开始:
摇双色结束:
已模拟摇双色共10000000次,统计结果如下:
双色点数合计 摇出次数  所占百分比:
2  278238  2.79%
3  557047  5.58%
4  833776  8.34%
5  1110028  11.11%
6  1387272  13.88%
7  1667303  16.68%
8  1389705  13.90%
9  1111055  11.12%
10  832604  8.33%
11  554908  5.55%
12  278064  2.79%
校验值-摇出次数合计:10000000,概率合计:1.00,百分比合计:100.05



0 0
原创粉丝点击