.编程生成 100个1~6之间的随机数,统计1~6之间的每个数出现的概率:修改程序,使之生成 1000个随机数并统计概率;比较不同的结果并给出结论Java
时间: 2024-03-06 14:50:18 浏览: 33
以下是生成100个1~6之间的随机数并统计每个数出现的概率的Java代码:
```java
import java.util.Random;
public class Probability {
public static void main(String[] args) {
Random random = new Random();
int[] randomNumbers = new int[100];
// 生成100个1~6之间的随机数
for (int i = 0; i < 100; i++) {
randomNumbers[i] = random.nextInt(6) + 1;
}
// 统计每个数出现的次数
int[] counts = new int[6];
for (int num : randomNumbers) {
counts[num - 1]++;
}
// 计算每个数出现的概率
double[] probabilities = new double[6];
for (int i = 0; i < 6; i++) {
probabilities[i] = (double) counts[i] / 100;
}
// 输出结果
for (int i = 0; i < 6; i++) {
System.out.printf("%d出现的概率为: %.2f\n", i + 1, probabilities[i]);
}
}
}
```
运行结果可能如下:
```
1出现的概率为: 0.22
2出现的概率为: 0.17
3出现的概率为: 0.17
4出现的概率为: 0.20
5出现的概率为: 0.13
6出现的概率为: 0.11
```
以下是生成1000个1~6之间的随机数并统计每个数出现的概率的Java代码:
```java
import java.util.Random;
public class Probability {
public static void main(String[] args) {
Random random = new Random();
int[] randomNumbers = new int[1000];
// 生成1000个1~6之间的随机数
for (int i = 0; i < 1000; i++) {
randomNumbers[i] = random.nextInt(6) + 1;
}
// 统计每个数出现的次数
int[] counts = new int[6];
for (int num : randomNumbers) {
counts[num - 1]++;
}
// 计算每个数出现的概率
double[] probabilities = new double[6];
for (int i = 0; i < 6; i++) {
probabilities[i] = (double) counts[i] / 1000;
}
// 输出结果
for (int i = 0; i < 6; i++) {
System.out.printf("%d出现的概率为: %.2f\n", i + 1, probabilities[i]);
}
}
}
```
运行结果可能如下:
```
1出现的概率为: 0.17
2出现的概率为: 0.19
3出现的概率为: 0.17
4出现的概率为: 0.16
5出现的概率为: 0.16
6出现的概率为: 0.15
```
对比不同数量的随机数生成结果,可以发现,随着生成的随机数数量增多,每个数出现的概率越接近1/6。这符合大数定律。因此,我们可以得出结论:随着样本数量的增加,样本统计结果越接近真实的概率值。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)