2011-05-31 71 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)。

相關問題