简体   繁体   English

程序陷入无限循环

[英]Program stuck in Infinite loop

My program is going in infinite loop and does not print required output please help anyone我的程序进入无限循环,不需要打印 output 请帮助任何人

图片

On the 2nd and subsequent iterations of the outer while loop, space will be initialized with a non-zero value, and then the while(space) loop will keep incrementing space for a long time until it overflows to a negative value, and then keep looping for a long time further until space eventually increments to 0, finally breaking the loop.在外层while循环的第2次及后续迭代中, space会被初始化为一个非零值,然后while(space)循环会长时间保持递增space ,直到溢出为负值,然后保持进一步循环很长时间,直到space最终增加到 0,最终打破循环。 When an int is evaluated as a boolean, only 0 evaluates as false, all other values evaluate as true.当一个int被评估为 boolean 时,只有 0 被评估为 false,所有其他值被评估为 true。 And a 32bit int can hold 4294967296 unique values (-2147483648..2147483647), giving the illusion that your loop is infinite.一个 32 位的int可以保存 4294967296 个唯一值(-2147483648..2147483647),给人一种循环是无限的错觉

while(space)
{
    std::cout << ' ';
    space = space + 1;
}

When space is 1 , this loop will increment i , so it keeps looping.space1时,此循环将增加i ,因此它会继续循环。 It will loop until space overflow, and increment until space is 0它将循环直到space溢出,并递增直到space0

You probably want:你可能想要:

while(space)
{
    std::cout << ' ';
    --space;
}

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

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