我想知道,由于我正在学习Java从教程,有一个程序,滚动骰子1000次,并打印其频率。
import java.util.Random;
public class RollDicewitharray {
public static void main(String[] args) {
Random r=new Random();
int arr[]= new int[7];
System.out.println("diceNo.\tFrequency");
for (int roll = 1; roll < 1000; roll++) {
++arr[1+r.nextInt(6)]; /* this line */
}
for (int i = 1; i < arr.length; i++) {
System.out.println(i+"\t"+arr[i]);
}
}
发布于 2016-02-25 04:25:58
r.nextInt(6)
生成一个介于0到5之间的随机整数,在它中添加1会给你在1到6之间的随机掷骰子。
arr
数组用于计数每个骰子卷发生的次数,因此++arr[1+r.nextInt(6)]
会增加当前卷的计数。
当第一个循环完成时,arr[1]
保存1s的数目,arr[2]
保持2s的数目,依此类推。
发布于 2016-02-25 04:30:50
总之,这个程序模拟滚动一个六边骰子1000次,并记录每个数字滚动的事件。
public static void main(String[] args) {
Random r=new Random();
int arr[]= new int[7]; //Craete an array with 7 int elements
System.out.println("diceNo.\tFrequency");
for(int roll=1;roll<1000;roll++){ //Loop 1000 times
++arr[1+r.nextInt(6)]; //Randomly pick arr[1] to
} //arr[6] and plus one to it
for(int i=1;i<arr.length;i++){
System.out.println(i+"\t"+arr[i]); //Print occurrence of 1-6
}
}
破解以下代码:
++arr[1+r.nextInt(6)]; //r.nextInt(6) will be evaluated first:
r.nextInt(6)
返回(0-5)
的随机值,因此您有:
++arr[1+(random 0 to 5)]; //+1 will be evaluated next:
因此,您正在生成1-6
的随机值。接下来,将1添加到数组中:
++arr[random 1 to 6]; //+1 to arr[1] or arr[2] or arr[3] or arr[4] or arr[5] or arr[6]
现在可以解释为:
arr[1] +=1; //or
arr[2] +=1; //or
arr[3] +=1; //or
arr[4] +=1; //or
arr[5] +=1; //or
arr[6] +=1;
因此,在运行程序之后,如果您的数组如下所示:
[0] [1] [2] [3] [4] [5] [6] Array index
+---+---+---+---+---+---+---+
| 0 |175|170|165|170|165|175| <-- arr
+---+---+---+---+---+---+---+
It means 1 was rolled 175 times,
2 was rolled 170 times,
3 was rolled 165 times,
and so on..
发布于 2016-02-25 04:26:06
1 + r.nextInt(6)
绘制一个从1到6的随机数。
++arr[1 + r.nextInt(6)];
增加数组arr
的元素。
因此,建立了骰子的频率分布。不使用数组的第零元素。这就是为什么它被设置为7个元素。也许是浪费?你来告诉我。
https://stackoverflow.com/questions/35627203
复制相似问题