代码是运行模拟来找出 n 个人生日相同的概率。
我将随机分配的生日与一组日期进行了比较。对于任何具有超过 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);
}
}