问题
This loop won't terminate if I add an OR conditional statement. If one is false, then it should terminate.
//global var
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);
}
回答1:
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.
Perhaps you wanted:
while((strncmp(n, "n", 1) != 0) && x != 100);
Which would terminated the loop if either of the two conditions is false.
&&
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.
回答2:
The while
loop will execute as long as the entire condition evaluates to 1
, or true. If x
is never 100
, then the logical OR in your condition will always be true, because one of it's operands is true.
x
begins at 100
, and each time through the loop, you increment x
. So before you ever test x
in the loop condition, it is greater than 100 - it's 101 - and always increases.
回答3:
You picked the wrong boolean operator. If you type n, and x is equal to 10, the while condition simplifies like this:
while((strncmp(n, "n", 1) != 0) || x!=100 ); while((0 != 0) || (10!=100) ); while(0 || 1) while(1)
Since each comparison is already a NOT, you want && instead of ||
回答4:
Checking numeric equality to terminate a loop is usually a bad idea. You want to check for a range of values, e.g., x < 100
.
Hence, the classic for
loop test is i < n
and not i != n
.
I only terminate loops with equality when the variable is a boolean type.
回答5:
the condition x!=100 is never going to be false, since x is already incremented to 101 when the first do while is executed so to make the statement false u should use && in place of ||
来源:https://stackoverflow.com/questions/12114453/while-loop-wont-terminate-with-a-logical-conditional