while循环不会以逻辑条件终止 [英] while loop won't terminate with a logical conditional
问题描述
如果添加OR条件语句,此循环不会终止.如果为假,则应终止.
This loop won't terminate if I add an OR conditional statement. If one is false, then it should terminate.
//全局变量
int x = 100;
char *n= malloc (64);
void add(void)
{
do
{
printf("Would you like to add 1? (y/n) ");
fgets(n, 64, stdin);
//removes newline
n[strlen(n)-1] = '\0';
x++;
}
//if I add || (x!=100) it keeps looping me even if I press "n"
//otherwise without it it works fine
while((strncmp(n, "n", 1) != 0) || x!=100 );
free(n);
}
推荐答案
在循环的底部,您正在执行x++
.遇到while条件x == 101
后,因此循环永远不会终止,检查条件时x
永远不会等于100.
At the bottom of your loop, you're doing x++
. Once you hit the while condition, x == 101
, so your loop never terminates, x
never equals 100 when the condition is being checked.
也许您想要:
while((strncmp(n, "n", 1) != 0) && x != 100);
如果两个条件中的任何一个为假,哪个会终止循环.
Which would terminated the loop if either of the two conditions is false.
&&
是逻辑和"运算符,||
是逻辑或"运算符.为了帮助您跟踪,可以使用 Truth Table 来帮助您整理详细信息.逻辑,与逻辑合取和逻辑相同,或与逻辑析取相同.
&&
is the 'logical and' operator, ||
is the 'logical or' operator. To help you keep track, you can use a Truth Table to help you sort out the details. Logical and is the same as logical conjunction and logical or is the same as logical disjunction.
这篇关于while循环不会以逻辑条件终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!