使用java无法实现预期结果,但使用c#是

Jas*_*son 0 c# java random

我有一个程序,旨在模拟一些概率问题(如果你感兴趣的话,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);
    }

}
Run Code Online (Sandbox Code Playgroud)

Oli*_*rth 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
}
Run Code Online (Sandbox Code Playgroud)