java中Math 的 random 方法用来实现什么功能?语句(int)(Math.random()*6)+1 的作用是什 么? (1)编写测试程序:在测试程序中生成 100 个 1~6 之间的随机数,并统计 1~6 每个数 出现的概率; 第 2 页 (2)修改上面的程序生成 1000 个随机数并统计概率;比较不同的结果并给出结论。
时间: 2023-06-27 17:01:04 浏览: 132
Java中的Math.random()方法用来生成一个0到1之间的随机数,包括0但不包括1。因此,为了生成一个1到6之间的随机数,可以使用语句(int)(Math.random()*6)+1,其中Math.random()*6生成一个0到5之间的随机数,加1后就可以得到1到6之间的随机数。
对于第一个问题,可以编写如下的测试程序来实现:
```
public class RandomTest {
public static void main(String[] args) {
int[] count = new int[6];
for (int i = 0; i < 100; i++) {
int num = (int)(Math.random() * 6) + 1;
count[num - 1]++;
}
for (int i = 0; i < 6; i++) {
System.out.println("Number " + (i+1) + " appears " + count[i] + " times, probability is " + (double)count[i]/100);
}
}
}
```
运行该程序,可以得到每个数字出现的次数和概率,例如:
```
Number 1 appears 13 times, probability is 0.13
Number 2 appears 11 times, probability is 0.11
Number 3 appears 22 times, probability is 0.22
Number 4 appears 16 times, probability is 0.16
Number 5 appears 16 times, probability is 0.16
Number 6 appears 22 times, probability is 0.22
```
对于第二个问题,只需要将上面程序中的循环次数改为1000即可,例如:
```
public class RandomTest {
public static void main(String[] args) {
int[] count = new int[6];
for (int i = 0; i < 1000; i++) {
int num = (int)(Math.random() * 6) + 1;
count[num - 1]++;
}
for (int i = 0; i < 6; i++) {
System.out.println("Number " + (i+1) + " appears " + count[i] + " times, probability is " + (double)count[i]/1000);
}
}
}
```
运行该程序,可以得到每个数字出现的次数和概率,例如:
```
Number 1 appears 169 times, probability is 0.169
Number 2 appears 167 times, probability is 0.167
Number 3 appears 162 times, probability is 0.162
Number 4 appears 161 times, probability is 0.161
Number 5 appears 175 times, probability is 0.175
Number 6 appears 166 times, probability is 0.166
```
可以发现,当循环次数增加时,每个数字出现的概率更接近于1/6。因此,可以得出结论:随着循环次数的增加,随机数生成的结果更加接近于理论概率。
阅读全文