简体   繁体   English

即使满足条件,while循环也不会中断

[英]while loop is not breaking even if the condition is satisfied

I have created a program to print armstrong number, but the inner while loop is not breaking, it should break when the value is 0, but it is going into continuous loop. 我已经创建了一个打印阿姆斯壮数字的程序,但是内部的while循环没有中断,当值为0时它应该中断,但是它将进入连续循环。

Can anyone tell me what's wrong in my program. 谁能告诉我我的程序出了什么问题。 Is this the correct behaviour of compiler. 这是编译器的正确行为吗?

#include<stdio.h>
int main()
{
        int i=1,n,a=0;
        while(i<=500)
        {
                printf("1st i = %d\n",i);
                while(i > 0)    //This loop is not breaking.
                {
                        printf("2nd i = %d\n",i);
                        n = i%10;
                        printf("n = %d\n",n);
                        a = n*n*n + a;
                        i = i/10;
                        printf ("3rd i = %d\n",i);
                        printf ("a = %d\n",a);
                        if (i==0)
                                break;
                }
                if (a==i)
                        printf("Number is Armstrong");
                i++;
        }
        return 0;
}

Please try running the program, it seems to be correct but it is not working. 请尝试运行该程序,它似乎是正确的,但无法正常工作。

You are using same variable (i) for both loops, and in the inner loop the condition of exit is i being 0 or negative, but the only change in this variable in the inner loop is i=i/10 which usually gives unexpected results when using with int. 您在两个循环中都使用相同的变量(i),在内部循环中,退出的条件是i为0或负数,但是内部循环中此变量的唯一变化是i=i/10 ,这通常会产生意外结果与int一起使用时。

Also, the i will never reach 500 in the outer loop, as it is decreased in the inner loop. 而且,i在外循环中永远不会达到500,因为在内循环中它会减少。 I'm not sure why are you doing this, but check if you have to use the same variable in both loops 我不确定为什么要这样做,但是请检查两个循环中是否必须使用相同的变量

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

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