#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 打印其决定。
这是印刷的:
...
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,2,3,1,2,3的1,2,3,1,2,3,...订购:
door = door%3 + 1;
减少:
door = (door + 1)%3 + 1;
...或只是增加两次。