c - Monty hall show模拟出乎意料的结果

标签 c

#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/

相关文章:

c++ - 由于无符号算术运算符的环绕而导致的 MISRA 错误

c、printf、 double : getting more than 15 decimal digits

c - 获取用户输入,将其添加到数组中正确的索引处(升序)

c - STM32 HAL rx中断无法正确获取字节

c - 为什么应该执行 exec "sh -c a.out"而不是 a.out 本身?

c - 使用 read(..) 从 stdin 读取并计算出缓冲区的大小

c - 使用c语言编程从url获取文件内容

c - 为 C 打印扩展 ASCII 字符的好方法是什么?

c - Emacs -*- lang -* 标签和旧式 K&R C

我可以避免在数组的连续子集中写入相同值的循环吗?