Java输出问题?程序未获得所需结果[格式更新]
这个程序应该对2到50个人进行测试,并从100000次测试中得出两个人是否会有相同的生日的概率Java输出问题?程序未获得所需结果[格式更新],java,class,object,for-loop,while-loop,Java,Class,Object,For Loop,While Loop,这个程序应该对2到50个人进行测试,并从100000次测试中得出两个人是否会有相同的生日的概率 import java.util.Random; public class birthday { public static void main(String[] args) { int N = 2; while (N != 51) { double probability = one_probability(N);
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;
}
}
import java.util.Random;
公课生日{
公共静态void main(字符串[]args){
int N=2;
而(N!=51){
双概率=一个概率(N);
System.out.println(N+“”+概率);
N++;
}
}
公共静态布尔一组(int N){
int A[]=新的int[N];
随机=新随机();
布尔值have_match=false;
对于(inti=0;i
这是结果(从2-50开始),它一直给我零,所以我知道出了问题。请帮忙:)
将其转换为双概率=x/100000.0代码>概率值始终小于或等于1。因为x永远不会大于100000。并将one_probability
方法的返回类型更改为double
尝试
int probability = x / 1000; // 1/100 of the value to get an probability in percent (integer)
或
如果没有这一点,这是行不通的:
float probably = x / 100000;
首先,两个整数的除法将像整数一样存储在内存中,然后存储在float/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
将您的代码作为格式化文本发布在此处!不是作为一个形象!你调试代码了吗?一直为零,让我认为你在对一个整数进行除法。x
小于100000,你计算probability
作为一个整数=>应该是一个浮点数。我尝试将概率转换为一个双精度和一个浮点数,结果都得到了0.0作为答案。这将是我在这篇文章中做了一个完整运算的重复回答:我尝试将概率转换为双精度和浮点型,两种情况下都给我0.0作为答案,然后在计算概率之前检查x的值。它可能是0.ya,但为什么会是0,for循环会有什么问题?您不知道该操作符在JAVA中是如何工作的double=int/int
将返回一个int
,然后被转换成double
(因为它适合)。但该值已被截断…请使用x/100000.0而不是x/100000。它正在工作。我查过了worked@MichaelA. 如果你感兴趣的话,我做了一个更完整的回答
float probably = x / 100000;
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