我有一个旨在模拟一些概率问题的程序(如果你感兴趣的话,monty大厅问题的变体)。预期的结果不是用java实现的,而是用c#
代码预计经过足够的迭代后会产生50%,但在java中它总是达到60%(即使经过1000000次迭代),而在C#中出现预期的50%是否有一些不同我不知道关于Java的随机可能?
下面是代码:
import java.util.Random;
public class main {
public static void main(String args[]) {
Random random = new Random();
int gamesPlayed = 0;
int gamesWon = 0;
for (long i = 0; i < 1000l; i++) {
int originalPick = random.nextInt(3);
switch (originalPick) {
case (0): {
// Prize is behind door 1 (0)
// switching will always be available and will always loose
gamesPlayed++;
}
case (1):
case (2): {
int hostPick = random.nextInt(2);
if (hostPick == 0) {
// the host picked the prize and the game is not played
} else {
// The host picked the goat we switch and we win
gamesWon++;
gamesPlayed++;
}
}
}
}
System.out.print("you win "+ ((double)gamesWon/(double)gamesPlayed)* 100d+"% of games");//, gamesWon/gamesPlayed);
}
}
使用一个调试器,你会发现缺少一个'break;'子句。我建议你学习如何使用你的调试器。 (它通常在你的IDE中运行) – 2011-05-31 12:02:36
别担心我知道如何使用debbuger :) – Jason 2011-05-31 12:06:59
@Jason为什么主机会随机选择?主人知道门后是什么,所以永远不会选择奖品。 – dogbane 2011-05-31 12:07:26