2011-05-31 72 views
0

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

} 
+2

使用一个调试器,你会发现缺少一个'break;'子句。我建议你学习如何使用你的调试器。 (它通常在你的IDE中运行) – 2011-05-31 12:02:36

+0

别担心我知道如何使用debbuger :) – Jason 2011-05-31 12:06:59

+1

@Jason为什么主机会随机选择?主人知道门后是什么,所以永远不会选择奖品。 – dogbane 2011-05-31 12:07:26

回答

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 
} 
+0

哈哈,你是正确的我忘了在java版本。谢谢 – Jason 2011-05-31 12:03:29

3

你忘了休息的case语句的结束,所以情况(1)继续情形(3)。

相关问题