java:生日概率程序

时间:2015-09-22 03:02:03

标签: java probability

我正在尝试创建一个程序,找出一个房间里两个随机学生生日相同的概率。输入学生人数和模拟人数。每当我运行它时,有23名学生,我一直得到0.69,这与大约0.50的实际答案不一致。我认为这可能与以下事实有关:如果有3名学生同一个生日,则会将其视为3场比赛。但我不知道如何解决这个问题,我已经尝试了多次。我可以得到一些帮助吗?

import java.util.Scanner;

public class bday{
public static void main(String[] args){
    Scanner inp = new Scanner(System.in);
    System.out.println("How many students?");
    int num = inp.nextInt();
    System.out.println("How many times?");
    int times = inp.nextInt();
    double x[] = new double[num];
    int match = 0;
    for(int i=0;i<times;i++){
        for(int j=0;j<num;j++){
            x[j] = (int)(Math.random()*365)+1;
        }
        for(int j=0;j<num;j++){
            for(int k=j+1;k<num;k++){
                if(x[j]==x[k]){
                    match++;
                }
            }
        }
    }
    double prob = (double)match/times;
    System.out.println("The probability for two students to share a birthday is "+prob+".");
}}

1 个答案:

答案 0 :(得分:0)

你弄乱了逻辑。逻辑应该是这样的: 每当出现相同的生日时,您将在总匹配中添加一个,然后中断然后再次开始。完成所有时间后,将总匹配除以多少次。 这是代码:

import java.util.Scanner;

public class Test2 {
public static void main(String[] args) {
    Scanner inp = new Scanner(System. in );
    System.out.println("How many students?");
    int num = inp.nextInt();
    System.out.println("How many times?");
    int times = inp.nextInt();
    int x[] = new int[num];
    int matches = 0;
    boolean out = false;
    for (int i = 0; i < times; i++) {
        for (int j = 0; j < num; j++) {
            x[j] = (int)(Math.random() * 365) + 1;
        }
        for (int j = 0; j < num; j++) {
            for (int k = j + 1; k < num; k++) {
                if (x[j] == x[k]) {
                    matches++;
                    out = true;
                    break;
                }
            }
            if (out) {
                out = false;
                break;
            }
        }
    }
    double prob = (double) matches / times;
    System.out.println("The probability for two students to share a birthday is " + prob + ".");
}
}

测试结果:100000为0.50557,1000000为0.507591。应该接近你的答案。