C# java没有达到预期的结果,但c达到了预期的结果

C# java没有达到预期的结果,但c达到了预期的结果,c#,java,random,C#,Java,Random,我有一个模拟概率问题的程序,如果你感兴趣的话,它是monty hall问题的变种 在足够多的迭代之后,代码预计会产生50%,但在java中,即使在1000000次迭代之后,它也会达到60%,而在C中,它会达到预期的50%,我不知道java的随机性有什么不同吗 代码如下: import java.util.Random; public class main { public static void main(String args[]) { Random random

我有一个模拟概率问题的程序,如果你感兴趣的话,它是monty hall问题的变种

在足够多的迭代之后,代码预计会产生50%,但在java中,即使在1000000次迭代之后,它也会达到60%,而在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语句结束每个case块

为此:

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
}

您忘记在case语句的末尾加上分隔符,因此case1继续到case3。

使用调试器,您会看到一个分隔符;缺少第条。我建议您学习如何使用调试器。在你的想法中,它通常是下一个。别担心,我知道如何使用debbuger:@Jason为什么主持人随机挑选?主人知道门后是什么,所以永远不会选奖品。@Jason,我想你当时忘了用它了@杰森,兰登很好。你的问题是关于正确使用Random,因此你的标题很容易引起误解。我建议你改变它。哈哈,你是对的,我在java版本中忘记了这一点。谢谢