[英]C - While Loop Condition has OR with Char: Not Terminating
When using the logical OR operator in a while loop for Char values, the program does not run correctly.在 while 循环中对 Char 值使用逻辑 OR 运算符时,程序无法正确运行。
The code is the following:代码如下:
#include <stdio.h>
void main() {
char choice = 'y';
while( choice != 'n' || choice != 'N') {
int num;
printf("\nEnter any number: ");
scanf("%d", &num);
int i = num - 1;
while(i >= 1) {
num *= i;
i--;
}
printf("Factorial is: %d\n", num);
printf("Do you want to continue? \n");
printf("Enter n to quit or y to continue\n");
scanf(" %c", &choice);
}
}
Ouput:输出:
Enter any number: 3
Factorial is: 6
Do you want to continue?
Enter n to quit or y to continue
n
Enter any number: 3
Factorial is: 6
Do you want to continue?
Enter n to quit or y to continue
N
Enter any number:
If I change the while statement, for example, to:例如,如果我将 while 语句更改为:
while( choice != 'n' ) {
The program runs fine.程序运行良好。 It is the logical OR that is creating an error.
造成错误的是逻辑或。
Why is this issue occurring?为什么会出现这个问题? And how do I make the program run with the OR logical operator?
以及如何使程序使用 OR 逻辑运算符运行?
The logical OR operator ||
逻辑或运算符
||
evaluates to true if either expression is true.如果任一表达式为真,则计算结果为真。
So if choice
is N
then choice != 'n'
is true, and if choice
is n
then choice != 'N'
is true.因此,如果
choice
为N
,则choice != 'n'
为真,如果choice
为n
,则choice != 'N'
为真。 If choice
is neither of those, then both are true.如果
choice
两者都不是,那么两者都是正确的。 So the full condition will always be true.因此,完整条件将始终为真。
You want to instead use the logical AND operator &&
.您想改用逻辑 AND 运算符
&&
。 This evaluates to true only if both expressions are true.只有当两个表达式都为真时,它才会计算为真。
while( choice != 'n' && choice != 'N') {
If you put n
, choice != 'N'
is true and it continues.如果你把
n
, choice != 'N'
是真的,它会继续。
If you put N
, choice != 'n'
is true and it continues.如果你把
N
, choice != 'n'
是真的,它会继续。
There should be &&
instead of ||
应该有
&&
而不是||
. .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.