【发布时间】:2011-05-31 11:52:08
【问题描述】:
我有一个程序旨在模拟一些概率问题(如果您有兴趣,可以将其变种为 monty hall 问题)。
代码在足够的迭代后预计会产生 50%,但在 java 中它总是达到 60%(即使在 1000000 次迭代之后),而在 C# 中它达到预期的 50% 是否有一些不同的东西我不知道java的Random可能吗?
代码如下:
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 中运行旁边) -
别担心,我知道如何使用调试器:)
-
@Jason 楼主为什么随机选择?主持人知道门后是什么,所以永远不会挑选奖品。
-
@Jason,我想你当时忘了使用它。 ;)
-
@Jason,随机工作正常。您的问题是关于正确使用 Random ,因此您的标题非常具有误导性。我建议改变它。