嘿伙计们我试图获得生日相同的人数,但这个解决方案没有用。这个程序显示0.0%。请帮助我......!。
public double calculate(int size, int count) {
int matches = 0;//initializing an integer variable
boolean out = false;
List<Integer> days=new ArrayList<Integer>();// creating arraylist name days of type int
for (int j = 0; j <count; j++) {
for (int i = 0; i < size; i++) {// initializing for loop till less than size
Random rand = new Random(); // creating an object of random function
int Brday = rand.nextInt(364) + 0;//initializing the limit of randomc number chozen
days.add(Brday); //adding values to arraylist
}
for (int l = 0; l < size; l++) {
int temp = l;//assigning value of l to a variable
for (int k = l + 1; k < size; k++) {
if (days.get(k) == temp) {// check statement to check values are same
matches++;//incrementing variable
out = true;
mOut.print("Count does have same birthday" + matches);
break;
} else {
mOut.print("does not have same birthday");
}
}
if (out) {
out = false;
break;
}
}
}
double prob = (double) matches / count;
mOut.print("The probability for two students to share a birthday is " + prob*100 + ".");
return prob;//returning double value of the function
}
答案 0 :(得分:0)
实际上,您的代码获得0%或100%。如果您想查看,请尝试使用calculate(100, 100)
调用它。
此代码中有两个错误。首先,如果您多次运行模拟(count
> 1),那么您永远不会在第二次迭代之前清除生日列表。
您的方法应该以:
开头public double calculate(int size, int count) {
int matches = 0;
boolean out = false;
List<Integer> days;
for (int j = 0; j <count; j++) {
days = new ArrayList<Integer>();
其次,您不是比较两个生日,而是将生日与列表中的索引进行比较。
这一行:
int temp = l;//assigning value of l to a variable
应阅读:
int temp = days.get(l); // Remember the birthday at index l
通过这些更改,您将获得更好的结果。