寻求帮助,不太确定我的代码有什么问题。
假设人们一次进入一个房间。人们必须如何进入,直到两人生日相同?与直觉相反,在 23 人进入房间后,两人生日相同的概率约为 50–50。这种现象被称为生日问题或生日悖论。
编写一个程序 Birthday.java,接受两个整数命令行参数 n 和 trials 并执行以下实验,trials 次数:
在每个实验中,计算进入房间的人数。打印一个表格,总结 i 从 1 到分数达到的每个可能值的结果(计数 i,恰好 i 人进入房间的次数,以及 i 或更少的人进入房间的次数的分数) (或超过)50%。
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
double trials = Integer.parseInt(args[1]);
boolean[] birthday = new boolean[n];
double fraction = 0.0;
int r = 0;
int count = 0;
int sumCount = 0;
int Num_people = 1;
while (fraction < 0.5) {
for (int i = 0; i <= trials; i++) {
for (int j = 0; j < n; j++) {
birthday[j] = false;
}
for (int t = 0; t < Num_people; t++) {
r = (int) (Math.random() * n);
if (birthday[r] == false) {
birthday[r] = true;
}
else if (birthday[r] == true) {
count++;
break;
}
}
}
sumCount += count;
fraction = sumCount / trials;
System.out.println(Num_people + "\t" + count + "\t" + fraction);
count = 0;
Num_people++;
}
}
}
这是我的输出:
PS C:\Users\Desktop\Week3> java Birthday 365 1000000
1 0 0.0
2 2796 0.002796
3 8299 0.011095
4 16198 0.027293
5 27290 0.054583
6 40356 0.094939
7 55821 0.15076
8 74429 0.225189
9 94974 0.320163
10 116837 0.437
11 141151 0.578151
PS C:\Users\Desktop\Week3> java Birthday 31 1000000
1 0 0.0
2 32335 0.032335
3 94371 0.126706
4 182560 0.309266
5 288067 0.597333
这是预期的:
~/Desktop/arrays> java Birthday 365 1000000
1 0 0.0
2 2710 0.00271
3 5547 0.008257
4 8105 0.016362
5 10776 0.027138
6 13413 0.040551
7 15782 0.056333
8 17816 0.074149
9 20283 0.094432
10 22297 0.116729
11 24105 0.140834
12 26013 0.166847
13 27247 0.194094
14 28405 0.222499
15 29873 0.252372
16 30447 0.282819
17 31445 0.314264
18 31837 0.346101
19 32559 0.37866
20 32244 0.410904
21 32357 0.443261
22 32020 0.475281
23 31667 0.506948
~/Desktop/arrays> java Birthday 31 1000000
1 0 0.0
2 32270 0.03227
3 62580 0.09485
4 87582 0.182432
5 105596 0.288028
6 114427 0.402455
7 115494 0.517949
感谢您的帮助。 :)