关于掷两个骰子,得到数之和的统计

本文介绍了一个使用Java编写的掷骰子模拟程序。该程序通过36,000次模拟掷两颗骰子的过程,并记录每种可能点数之和出现的频率。通过这个实验,可以验证不同点数出现的概率分布是否符合预期。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(Dice Rolling)Write an application to simulate the rolling of two dice. The application should use an object of class Random once to roll the first die and again to roll the second die. The sum of the two values should than be calculated. Each die can show an integer value from 1 to 6, so the sum of the values will vary from 2 to 12, with 7 being the most frequent sum, and 2 and 12 the least frequent. Figure shows the 36 possible combinations of the two dice. Your application should roll the dice 36,000 times. Use a one-dimensional array to tally the number of times each possible su appears.Display the result in tabular format. Determine whether the totals are reasonable(e.g.,there are six ways to roll a 7, so approximately one-sixth of the rolls should be 7).

package array;
import java.util.*;

public class random{
	public static void main(String[] args) {
		int intArray[]= {0,0,0,0,0,0,0,0,0,0,0};
		java.util.Random b=new java.util.Random();//获得随机数b
		for(int i=0;i<36000;i++){
			int a=b.nextInt();
			int c=b.nextInt();//将随机数b复制给a和c
			if(a<0) {
				a=-a;
			}
			//将负的a取正
			a=a%6;
			a=a+1;
		    //获得1~6的随机数a
			if(c<0) {
				c=-c;
			}
			c=c%6;
			c=c+1;
			
			int x=a+c;
			switch (x) {
			case 2:
				intArray[0]++;
				break;
			case 3:
				intArray[1]++;
				break;
			case 4:
				intArray[2]++;
				break;
			case 5:
				intArray[3]++;
				break;
			case 6:
				intArray[4]++;
				break;
			case 7:
				intArray[5]++;
				break;
			case 8:
				intArray[6]++;
				break;
			case 9:
				intArray[7]++;
				break;
			case 10:
				intArray[8]++;
				break;
			case 11:
				intArray[9]++;
				break;
			case 12:
				intArray[10]++;
				break;
			}
		}
		for(int o=0;o<11;o++)
		System.out.println(intArray[o]);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值