gpt4 book ai didi

java - 查找重复的生日 (Java)

转载 作者:行者123 更新时间:2023-12-01 11:08:23 25 4
gpt4 key购买 nike

该代码用于运行模拟来找出 n 个人生日相同的概率。

我将随机分配的生日与一组日期进行比较。对于任何具有超过 1 个等值的日期,我在分子上加了 1。

但是,代码的答案是错误的。我不知道为什么。

import java.util.Scanner;
public class birthday {
public static void main (String[] args) {

Scanner inp = new Scanner(System.in);

System.out.println("How many trials");
int n = inp.nextInt();

//variable declaration
double[] birthdate = new double[n];
int num = 0;
int numerator = 0;
double bday = 0;
int trials = 0;

//assign birthdays to n people
for (int i = 0; i < n; i++)
{
birthdate[i] = Math.floor(Math.random() * 365) + 1;
System.out.println(birthdate[i]);
}

for (int i = 1; i <= 365; i++)
{
for (int j = 0; j < n; j++)
{
bday = birthdate[j];

//compare birthdates to dates
if (bday == i)
{
num++;
if (num > 1)
{
numerator++;
}
}
}
num = 0;
}

double ans = (double) numerator / n;
System.out.println("The answer is " + ans);

}
}

最佳答案

For any dates that has more than 1 equal value, I added one to the numerator.

这不是你的代码的作用。对于任何至少有 2 个人在该日期过生日的日期,您将这些人的数量减去 1 到分子中。

如果你想让你的代码按照上面的语句工作,你必须更改以下代码

for (int j = 0; j < n; j++)
{
bday = birthdate[j];

//compare birthdates to dates
if (bday == i)
{
num++;
if (num > 1)
{
numerator++;
}
}
}
num = 0;

这段代码:

for (int j = 0; j < n; j++)
{
bday = birthdate[j];

//compare birthdates to dates
if (bday == i)
{
num++;
}
}
if (num > 1)
{
numerator++;
}
num = 0;

这样,代码 if (num > 1) numerator++ 就不会为每个人重复(从第二个开始),而是每个日期只执行一次。

无论如何,我怀疑这两个版本的代码是否能计算出“n 个人生日相同的概率”。如果这就是你想要的近似值,你应该多次重复整个实验,计算其中有多少个 n 人共享他们的生日,然后除以实验次数:

import java.util.Scanner;

public class birthday {
public static void main(String[] args) {

Scanner inp = new Scanner(System.in);

System.out.println("How many trials?");
int numExperiments = inp.nextInt();

System.out.println("How many persons?");
int n = inp.nextInt();

// variable declaration
int dups = 0;
for (int k = 0; k < numExperiments; k++) {
boolean foundDup = false;
int[] birthdate = new int[n];

// assign birthdays to n people
for (int i = 0; i < n; i++) {
birthdate[i] = (int) (Math.random() * 365) + 1;
}

// check, if there is a duplicate
for (int i = 1; i <= 365; i++) {
int num = 0;
for (int j = 0; j < n; j++) {
// compare birthdates to dates
if (birthdate[j] == i) {
num++;
}
}
if (num > 1) {
foundDup = true;
}
num = 0;
}

// count cases with duplicates
if (foundDup) {
dups++;
}
}

double ans = (double) dups / numExperiments;
System.out.println("The answer is " + ans);
}
}

关于java - 查找重复的生日 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32674644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com