#include <stdio.h>
#include <time.h>
int main (void)
{
int pickedDoor, remainingDoor, hostDoor, winningDoor, option, games = 0, wins = 0;
float frequency = 0;
srand (time(NULL));
while (1)
{
printf ("Pick one of the three doors infront of you, which do you want?\n");
scanf ("%d", &pickedDoor);
if (pickedDoor > 3 || pickedDoor <= 0)
{
break;
}
winningDoor = rand() % 3 + 1;
do
{
hostDoor = rand() % 3 + 1;
} while (hostDoor == pickedDoor || hostDoor == winningDoor);
do
{
remainingDoor = rand() % 3+1;
} while (remainingDoor == pickedDoor || remainingDoor == hostDoor);
printf ("The door the host picked is %d\n", hostDoor);
do
{
printf("Do you want to switch doors? Please enter in the door you want:\n", hostdoor);
scanf("%d", &option);
if (option > 3 || option <= 0)
{return 0;}
}while (option == hostDoor);
if (option == winningDoor)
{
printf("You Won!\n");
wins++;
}
else
{
printf("YOU LOSE!\n");
}
games++;
}
frequency = ((float) wins / games) *100;
printf ("The number of games that you won is %d\n", wins);
printf ("The frequency of winning is %.0f%%\n", frequency);
return 0;
}
嗨,这是我的 monty hall 游戏秀版本,不过我得到了意想不到的结果。
有时,当我进入一扇门进行选择时,它只会让我回到“从你面前的三扇门中选择一扇”的语句,此时它应该告诉我我是赢了还是输了。
我认为这是因为“选项”门等于“主机门”。
我认为使用“option != hostDoor”可以解决问题,但事实并非如此。
如果我的假设是正确的,我该如何解决?如果不是,为什么它不起作用,我该如何解决?
最佳答案
为了正确模拟,OP 需要显示主机门。
do {
printf("Do you want to switch doors? Please enter in the door you want:\n");
scanf("%d", &option);
if (option > 3 || option <= 0 ) {
return 0;
}
} while (option == hostDoor);
// instead of
#if 0
printf("Do you want to switch doors? Please enter in the door you want:\n");
scanf("%d", &option);
if (option > 3 || option <= 0 ) { return 0; }
#endif
处理 OP “它应该告诉我我是赢了还是输了。”问题,改变
else if (option == remainingDoor)
到
else
您的 scanf("%d", &option)
没问题。我更喜欢 fgets()/sscanf()
组合,它对于检查 scanf()
系列的结果总是很有用,但这不是你的问题。
关于c - Monty hall show模拟出乎意料的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19802210/