Monty Hall游戏:如何打印计算机打开的门

时间:2012-10-28 23:56:16

标签: c loops random printf scanf

#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并选择是否在程序打开其中一个假门时切换门。

如何让程序打开一扇门,这扇门必须在一扇门后面没有奖品,而且用户不会选择 AND 打印其决定。

以下是IS打印的内容:

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

感谢你的帮助。谢谢你和欢呼!

1 个答案:

答案 0 :(得分:0)

如果门是选定的门和/或奖品门,只需选择一个随机门并增加或减少门号。

要增加到1,2,3,1,2,3的下一个门,...顺序:

door = door%3 + 1;

递减:

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

...或者只增加两次。