java - 我的生日问题代码没有打印任何东西
问题描述
我是学习编程的绝对初学者,我得到了这个任务:
生日问题。假设人们一次进入一个房间。人们必须如何进入直到两个人共享生日?与直觉相反,在 23 人进入房间后,两人生日相同的概率约为 50-50。这种现象被称为生日问题或生日悖论。编写一个程序 Birthday.java,它接受两个整数命令行参数 n 和试验,并执行以下试验,试验次数:
- 为下一个人选择生日,在 0 和 n-1 之间均匀随机。
- 让那个人进入房间。
- 如果该人与房间里的其他人共享生日,请停止;否则重复。
在每个实验中,计算进入房间的人数。打印一张表格,总结从 1 到分数达到的每个可能值 i 的结果(计数 i、恰好 i 人进入房间的次数以及 i 或更少人进入房间的次数) (或超过)50%。
但是,我的代码不会打印。如果有人能帮助我找到我的作业的问题,我将不胜感激。
public class Birthday {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]); //number of days
int trials = Integer.parseInt(args[1]);
boolean[] birthdays = new boolean[n];
int[] times = new int[n + 2]; //number of times i people entered the room
int r;
for (int t = 1; t <= trials; t++) {
for (int k = 0; k < n; k++) { //reset birthday
birthdays[k] = false;
}
for (int i = 1; i <= n; i++) { //number of times
r = (int) (Math.random() * (n - 1)); //random birthday
if (birthdays[r] = false) {
birthdays[r] = true;
continue;
}
else if (birthdays[r] = true) {
times[i]++; //number of times i people entered the room + 1
break;
}
}
}
int j = 1;
while ((double) times[j] / trials <= 0.5) {
System.out.print(j + "\t" + times[j] + "\t" + ((double) times[j] / trials));
j++;
System.out.println("");
}
}
}
解决方案
我可以从您的代码中发现两个错误
正如可怕的袋熊指出的那样,您的 if 语句中缺少双等号。
该作业要求您计算“我或更少人进入房间的时间分数”,这意味着您需要对第一个
i
指数进行求和并除以试验。
例如,在 100 万次试验中,当第 4 个人进入时,第一个重复生日发生的比例是
(times[0] + times[1] + times[2] + times[3])/ 1000000
这是我得到的:
1 0 0.0
2 2810 0.00281
3 5428 0.008238
4 8175 0.016413
如您所见,分数是通过将前三个元素相加然后除以 1000000 来计算的(2810 + 5428 + 8175 = 16413) / 1000000 = 0.016413
您计算分数((double) times[j] / trials)
的方式不正确。
推荐阅读
- twitter - 如何将直接消息发送到我的 webhook url
- apache-kafka - 在马拉松比赛中出现重试退避错误并且没有重新启动 kafka-streams
- eclipse - OpenCL 错误:CL_INVALID_PROGRAM OpenCL 错误:CL_INVALID_PROGRAM
- flutter - 如何在flutter中实现类似iOS SplitView的效果
- javascript - 未找到模块:错误:无法解析“@deck.gl/experimental-layers”
- redux - 传递给 Redux reducer 时为 Immutable.js Map 键入注释
- ios - 删除两个或多个 '\r' '\n'
- regex - Shell脚本,替换下划线+空格+可能的数字
- keras - 如何在 keras 中实现对序列到序列模型的注意。请逐步解释
- arrays - 具有数学属性的 Excel VBA 字符串转换