Java输出问题?程序未获得所需结果[格式更新]



该程序应该经历2至50人的数量,并在100,000个试验中获得概率,无论2个人是否有相同的生日。

import java.util.Random;
public class birthday {
    public static void main(String[] args) {
        int N = 2;
        while (N != 51) {
            double probability = one_probability(N); 
            System.out.println(N + "  " + probability);
            N++;
        }
    }
    public static boolean one_group(int N) {
        int A[] = new int[N]; 
        Random random = new Random();
        boolean have_match = false; 
        for (int i = 0; i < N; i++) {  //assigns each person a birthday
            int k = random.nextInt(365);
            A[i] = k;
        }
        for (int i = 0; i < N; i++) {  //testing to see if birthdays match up
            for (int j = i+1; j < N; j++) {
                if (A[i] == A[j]) { have_match = true; break; }
            }
        }
        return have_match;
    }
    public static double one_probability(int N) { 
        int x = 0;
        for (int i = 0; i < 100000; i++) {  //repeating 100,000 times to get average probability
            boolean have_match = one_group(N);
            if (have_match == true) { x++; }
        }
        double probability = x / 100000;  //getting the average probability
        return probability;
    }
}

这是结果(从2-50开始),它不断给我零,所以我知道有问题。请帮忙 :)输出

尝试

int probability = x / 1000; // 1/100 of the value to get an probability in percent (integer)

float probably =  x / 100000F; //F for a `float` 
double probability = x / 100000.0; //a decimal without a F is a `double`

没有此事,这是行不通的:

float probably = x / 100000;

首先,两个整数的划分将存储在内存中,例如整数,然后将其存储在浮点/double中。该存储将截断值截断。这是返回操作中最大类型的操作员逻辑:

int * int -> int
int * float -> float
int * double -> double
short * short -> int //that's a trick, int is the minimal value an operation can return
int probability=x/100000; always return 0.

将其转换为double probability=x/100000.0;概率的值始终小于或等于一个。因为X永远不会大于100000。还将one_probability方法的返回类型更改为double

最新更新