我有一个程序,旨在模拟一些概率问题(如果你感兴趣,可以改变monty hall问题)。
在经过足够的迭代之后,代码预计会产生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);
}
}
答案 0 :(得分:9)
至少,您忘记使用case
语句结束每个break
块。
所以对此:
switch (x)
{
case 0:
// Code here will execute for x==0 only
case 1:
// Code here will execute for x==1, *and* x==0, because there was no break statement
break;
case 2:
// Code here will execute for x==2 only, because the previous case block ended with a break
}
答案 1 :(得分:3)
你忘了在案例陈述的最后放置休息,所以案例(1)继续到案例(3)。