while loop won't terminate with a logical conditional

懵懂的女人 提交于 2019-12-02 11:19:39

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.

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.

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 ||

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.

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 ||

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!