简体   繁体   English

在do while循环中即使条件为true也会循环返回

[英]Looping back even the Condition is true in do while loop

When i input negative integer it still loop back 当我输入负整数时,它仍会循环返回

#include <stdio.h>
#include <math.h>

int main() {
    int n,i,z;

    do {
        printf("Input: ");
        scanf(" %d",&n);
        z=z+n;
    } while (n != 0 || n < 0);

    printf("Sum:%d",z);     
}

Your code invokes Undefined Behavior (UB), since it tries to sum into z , while z is used uninitialized. 您的代码将调用未定义行为 (UB),因为它试图求和为z ,而未初始化使用z

Initialize it to zero. 初始化为零。


This condition says: 这种情况说:

while (n != 0 || n < 0);

as long as n has a different value from 0 OR is less than 0, loop again. 只要n的值不同于0或小于0,请再次循环。

I guess you want to stop looping, when input is a negative number, which means that you need this: 我猜您想在输入为负数时停止循环,这意味着您需要这样做:

while (n >= 0);

which means to continue executing the body of the do-while loop, as long as n is non negative (ie 0 or a positive number). 这意味着只要n为非负数(即0或正数),就可以继续执行do-while循环的主体。

But, notice that with that structure in your for loop, you will get the negative number (which it seems that you like it to be the break signal for your loop), extracted from your sum, z . 但是,请注意,在for循环中使用该结构后,您将从总和z提取负数(似乎您希望它是循环的中断信号)。

If you don't want that to happen, you can use the keyword break , to stop the loop from executing. 如果您不希望发生这种情况,则可以使用关键字break来停止执行循环。

Not sure what you expect this to do: 不知道您期望这样做吗:

while (n != 0 || n < 0);

translating it to natural language, it says " loop as long as n either isn't 0 or is smaller than 0 ". 将其翻译成自然语言,它说:“ 只要n不为0或小于0 ,就循环 ”。

I guess it's now obvious the second condition implies the first one? 我想现在很明显,第二个条件意味着第一个条件? This loop will only exit when n is exactly 0 . 仅当n正好为0时,此循环才会退出。


Note this isn't the only error: You're happily using z without ever initializing it, so you can get any value in the end (the initial value of z is indeterminate ) 请注意,这不是唯一的错误:您很乐意使用z而不进行初始化,因此最终可以得到任何值( z的初始值是不确定的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM