c - 如何更改我的程序以结束连续打印的错误响应?
问题描述
我编写了一个石头剪刀布程序,除了一件事之外,一切都很好。在 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 命令,但即使这样也不能解决问题。我必须在我的程序中进行哪些更改才能解决此问题?
解决方案
条件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
(即,如果choice
是1
,2
或中的任何一个3
)。
注意:上面并没有完全解释您的示例输入会发生什么(尽管我猜测外部while
循环结束并且您没有显示的代码然后显示计算机的选择);为此,我们需要查看更多代码,以便它是一个最小的、可编译的、可重现的示例。
推荐阅读
- python-2.7 - 我们可以在 Get Json Value 键中传递多个参数吗?
- c++ - 如何从流服务器接收消息?
- node.js - 具体值的 ElasticSearch 数据类型
- c++ - 两对 TCP 服务器/客户端共享相同的代码,但只有一个客户端接收消息
- ios - 需要帮助防止 UIImagePickerController 在 IOS13 中旋转我的仅纵向 UIView
- machine-learning - 未知标签类型:'连续'..如何解决此错误
- linux - 如何在 Linux 上的 JavaFX 中将日语输入到 TextArea
- swift - 使用 SWXMLHash 反序列化 XML 序列
- integration - 添加 CBR 后,flowground 流不工作
- javascript - 如何使用打字稿修剪对象内部的对象