[英]Infinite While Loop In C
这段代码创建了一个无限循环,我想按照一些步骤将数字首次显示为0并打印该程序需要花费多少步骤
int debut,i;
printf("de (>= 1) ? ");
do
{
scanf("%d",&debut);
}
while (debut < 1);
int fin;
printf("a >= << << ) ? ");
do
{
scanf("%d",&fin) ;
}
while (fin < debut);
for (;debut<=fin;debut++){
i=0;
while(debut!=0)
{
if(debut%3==0)
{
debut+=4;
}
else if (debut%3!=0 && debut%4==0){
debut/=2;
}
else if (debut%3!=0 && debut%4!=0)
{
debut-=1;
}
i+=1;
}
printf("%d\n->%d",debut,i);
}
for(debut<=fin;debut++) {
while(debut!=0) {
//do stuff
}
//debut == 0, debut <= fin
}
好的,大量编辑我的答案。 我看错了循环。
为了进入for
循环, debut
必须是<=fin
。 每当fin
>0
且进入for
循环时,您就会陷入for
循环中。
您陷入了while
循环中,直到除非debut == 0
返回true
为止。 只要debut++ <= fin
,您就会陷入for
循环中。 您正在while
循环中修改debut
,但是fin
保持不变。 因此, while
循环将debut
减少为0
,并且for
循环每次都会进入下一个迭代。
简短的回答 :我怀疑您打算将while循环用于debut
的副本 ,而不是debut
。
debut == 3
和fin == 5
。 debut == 0
, fin == 5
和i == 12
。 debut
已减少为0
,因此,每次运行此代码时,在for循环迭代结束时,我们将拥有一个debut == 0
,这将导致for循环永不退出。 在代码中内联显示可能会更有用...
for (;debut<=fin;debut++){
// Let's assume we get here. We can assume some sane debut and fin values,
// such as the 3 and 5 suggested above.
int i=0;
while (debut != 0) {
// Stuff happens that makes debut go to zero.
}
// To get to this point, we __know__ that debut == 0.
// We know this because that's the condition in the while loop.
// Therefore, when we do the comparison in the for loop above for the
// next iteration, it will succeed over and over again, because debut
// has been changed to zero.
printf("%d->%d\n",debut,i);
}
就我个人而言,我怀疑您正在寻找一组数字的迭代次数。 对我来说,这听起来像是使用功能的理想之地。 我建议的代码看起来像这样。
#include <stdio.h>
int iterations(int debut) {
int i = 0;
while(debut!=0)
{
if(debut%3==0)
{
debut+=4;
}
else if (debut%3!=0 && debut%4==0){
debut/=2;
}
else if (debut%3!=0 && debut%4!=0)
{
debut-=1;
}
i+=1;
}
return i;
}
int main() {
int debut = 3;
int fin = 5;
for (;debut<=fin;debut++) {
printf("%d -> %d\n", debut, iterations(debut));
}
}
另外,仅出于注意的目的,请注意,在最后给出的示例代码中,我删除了所有输入的scanf代码。 它与您的实际问题无关,它减少了任何人都需要扫描才能了解问题所在的代码总数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.