首页 > 解决方案 > 如何更改我的程序以结束连续打印的错误响应?

问题描述

我编写了一个石头剪刀布程序,除了一件事之外,一切都很好。在 else 条件行中,即包含(choice != 1 || choice != 2 || choice != 3) 带有完成break;命令的 while 循环的行,它仅在输入一次像 4 这样的不正确输入但不是第二次时才起作用。

当第一次输入不正确的输入时,程序将再次要求输入,但如果您输入另一个不正确的输入,它将继续打印相同的 printf 行

printf("Please choose 1 for ROCK, 2 for PAPER or 3 for SCISSORS.\n"); 然后继续继续打印

Computer choice is ROCK. Please choose 1 for ROCK, 2 for PAPER or 3 for SCISSORS.

  while (counter != 10) {

    for (i=0;i<1;i++) {
      /* Generate a random number and restrict it to the range 1 to 3 */
      randNum = rand()%3+1;
      /*printf("A random number between 1 and 3: %d\n", randNum);*/
    }

    printf("Please choose 1 for ROCK, 2 for PAPER or 3 for SCISSORS.\n");

    scanf("%d", &choice);


    /* User picks an option */
    
      if ( choice == 1 ){
        printf("User choice is ROCK.\n");
      }
      else if ( choice == 2 ){
        printf("User choice is PAPER.\n");
      }
      else if ( choice == 3 ){
        printf("User choice is SCISSORS.\n");
      }  
      else {
        while (choice != 1 || choice != 2 || choice != 3) {
    
          printf("Please choose 1 for ROCK, 2 for PAPER or 3 for SCISSORS.\n");
          scanf("%d", &choice);
          break;
      }

    }

两次输入错误时的输出

Please choose 1 for ROCK, 2 for PAPER or 3 for SCISSORS.
4
Please choose 1 for ROCK, 2 for PAPER or 3 for SCISSORS.
4
Computer choice is ROCK.
Please choose 1 for ROCK, 2 for PAPER or 3 for SCISSORS.

我已经尝试过使用 break 命令,但即使这样也不能解决问题。我必须在我的程序中进行哪些更改才能解决此问题?

标签: cloopsfor-loopcounter

解决方案


条件choice != 1 || choice != 2 || choice != 3永远真。例如(正如您所注意到的),如果choice是 4,那么它将不等于1,因此第一个测试将为真,因此(当您将测试与逻辑OR组合时),整个条件也将为真。

但是,当为 1 时条件为真choice。因为,虽然第一个测试 ( choice != 1) 将是false,但第二个测试 ( choice != 2) 现在将为真(因为 1等于 2)。此外,没有可能的数字可以使所有三个测试(或者实际上,其中任何两个测试)都为假。

你想要的,而不是OR ( ||) 是一个逻辑AND ( &&)。此外,您break;在该循环中的语句将确保循环只运行一次(它不会破坏外while循环)。

//...
      else {
        while (choice != 1 && choice != 2 && choice != 3) {
    
          printf("Please choose 1 for ROCK, 2 for PAPER or 3 for SCISSORS.\n");
          scanf("%d", &choice);
      //  break; // This will end the `while` on the first loop, for ANY input!
      }
//...

这样,while循环将一直运行,直到三个测试中的任何一个评估为false(即,如果choice1,2或中的任何一个3)。


注意:上面并没有完全解释您的示例输入会发生什么(尽管我猜测外部while循环结束并且您没有显示的代码然后显示计算机的选择);为此,我们需要查看更多代码,以便它是一个最小的、可编译的、可重现的示例


推荐阅读