首页 > 解决方案 > 我的生日问题代码没有打印任何东西

问题描述

我是学习编程的绝对初学者,我得到了这个任务:

生日问题。假设人们一次进入一个房间。人们必须如何进入直到两个人共享生日?与直觉相反,在 23 人进入房间后,两人生日相同的概率约为 50-50。这种现象被称为生日问题或生日悖论。编写一个程序 Birthday.java,它接受两个整数命令行参数 n 和试验,并执行以下试验,试验次数:

在每个实验中,计算进入房间的人数。打印一张表格,总结从 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("");

        }
    }
}

标签: javaarrays

解决方案


我可以从您的代码中发现两个错误

  1. 正如可怕的袋熊指出的那样,您的 if 语句中缺少双等号。

  2. 该作业要求您计算“我或更少人进入房间的时间分数”,这意味着您需要对第一个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)的方式不正确。


推荐阅读