编写一个模拟同时掷骰子的程序。要用Math.random()模拟产生两个骰子,将两个结果相加,相加的和等于7的可能性最大,等于2和12的可能性最小。程序模投掷3600次,判断求和的结果是否合理。
时间: 2024-10-10 18:06:30 浏览: 79
为了编写一个模拟同时掷骰子的程序,我们首先需要创建一个函数,该函数生成1到6之间随机整数代表每个骰子的结果。然后我们将这两个随机数相加,记录每次投掷的结果,并计算总次数和各和出现的次数。最后比较实际统计数据与理论概率,看是否接近。
以下是使用Java语言的一个简单示例:
```java
import java.util.Random;
public class DiceRoller {
private static final int NUM_ROLLS = 3600;
private static final int NUM_SIDES = 6;
public static void main(String[] args) {
Random random = new Random();
int[] sums = new int[NUM_ROLLS];
for (int i = 0; i < NUM_ROLLS; i++) {
int dice1 = random.nextInt(NUM_SIDES);
int dice2 = random.nextInt(NUM_SIDES);
int sum = dice1 + dice2;
sums[sum]++;
}
System.out.println("Dice roll results:");
for (int sum : sums) {
double probability = (double) sum / NUM_ROLLS;
System.out.printf("Sum of %d: %d times (%.4f%%)\n", sum, sum, probability * 100);
}
// Check if the distribution is roughly as expected
double expectedProbabilityFor7 = 6 / (NUM_SIDES * NUM_SIDES); // Most common sum
double expectedProbabilityFor2And12 = 1 / (NUM_SIDES * NUM_SIDES); // Least common sum
System.out.printf("\nExpected:\n7: %.4f%%\n2 & 12: %.4f%%\n", expectedProbabilityFor7 * 100, expectedProbabilityFor2And12 * 2 * 100);
System.out.println("Observed:\n7: Actual proportion\n2 & 12: Actual proportion");
}
}
```
在这个程序中,我们模拟了3600次投掷,并统计了每次投掷的和。然后我们对比了理论上的最常见和最不常见和的实际比例,看看它们是否接近预期。
阅读全文
相关推荐


















