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;
}

这是运行 Monty Hall 游戏的代码,用户在其中从三扇门中选择一扇门。一扇门有奖,另外两扇是假的。用户选择门 1、2 或 3 并选择在程序打开其中一扇假门时是否切换门。

我怎样才能让程序打开一扇门,这扇门必须是后面没有奖品并且用户没有选择的门并打印它的决定。

这是打印的内容:

...
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.
...

我感谢您的所有帮助。谢谢你和欢呼!

4

1 回答 1

0

只需选择一扇随机门,如果门是所选门和/或奖品门,则增加或减少门号。

以 1,2,3,1,2,3,... 的顺序递增到下一个门:

door = door%3 + 1;

递减:

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

...或者只是增加两次。

于 2012-10-29T00:33:07.377 回答