2012-10-28 39 views
1
#include <stdio.h> 
#include <time.h> 

int main(void) 
{ 
    static int games = 0; 
    static int stayWins = 0; 
    static int switchWins = 0; 
    int chosenDoor; 
    int remainingDoor; 
    int revealedDoor; 
    int winningDoor; 
    int option; 

    printf("Type 0 to stop choosing and print results: "); 

    srand (time(NULL)); 
    do 
    { 
    printf("Choose door 1, 2, or 3: "); 
    scanf("%d",&chosenDoor); 

    if (chosenDoor==0) 
     break; 

    printf("Enter '1' for stay; Enter '2' for switch:"); 
    scanf("%d",&option); 

    winningDoor = rand() % 3 + 1; 
     do 
     { 
      revealedDoor = rand() % 3 + 1; 
     } while (revealedDoor == chosenDoor || revealedDoor == winningDoor); 

     do 
     { 
      remainingDoor = rand() % 3+1; 
     } while (remainingDoor == chosenDoor || remainingDoor == revealedDoor); 

     option = rand() % 2 + 1; 
     if (option == 1) 
     { 
      if (chosenDoor == winningDoor) 
      { 
       printf("You win.\n"); 
       stayWins++; 
      } 
      else 
      { 
       printf("You lose.\n"); 
      } 
     } 
     if (option == 2) 
     { 
      chosenDoor = remainingDoor; 
      if (chosenDoor == winningDoor) 
      { 
       printf("You win.\n"); 
       switchWins++; 
      } 
      else 
      { 
       printf("You lose.\n"); 
      } 
     } 
     games++; 
    } while (chosenDoor!=0); 

printf("Out of %d games, the contestant won %d times by staying with his/her original choice and won %d times by switching his/her choice.",games,stayWins,switchWins); 

    return 0; 
} 

這是一個運行蒙蒂廳遊戲的代碼,用戶從三扇門中選擇一扇門。一扇門有獎品,另外兩個是假的。用戶選擇門1,門2或門3,並選擇是否在程序打開其中一個錯誤門時切換門。Monty Hall遊戲:如何打印電腦打開的門

如何讓程序打開一扇門,這個門必須是一個後面沒有獎品的門,而不是由用戶打印其決定。

這裏是打印什麼:

... 
Choose door (1,2,3): 
Enter 1 for stay; 2 for switch: 
You win/lose. 
... 

這是我想打印:

... 
Choose door (1,2,3): 
Door X has been opened to reveal a false door. 
Enter 1 for stay; 2 for switch: 
You win/lose. 
... 

我感謝你的幫助。謝謝你,歡呼!

+2

Monty ** Hall **,不是嗎? –

+0

http://en.wikipedia.org/wiki/Monty_Hall_problem – Tim

+0

是的,我拼錯了遊戲的名字。道歉。 – user1742525

回答

0

只要選擇一個隨機的門,並且如果門是選定的門和/或獎品門,則增加或減少門號碼。

以遞增到下一門1,2,3,1,2,3,...順序:

door = door%3 + 1; 

要減小:

door = (door + 1)%3 + 1; 

...或只是增量兩次。