谁能帮助我找出此C代码中的问题?

时间:2018-10-18 12:02:39

标签: c

有人可以告诉我程序的问题吗?这是一个用C语言编写的程序,用于查找1到500之间的Armstrong数。我是编程的初学者,因此可以接受学习。

      #include <stdio.h>
        int main()
        {
        int number,originalNumber,remainder,result=0;
        number = 001;
        while (number <= 500)
        {
        originalNumber=number;
        while(originalNumber != 0)
        {
            remainder= originalNumber%10;
            result += remainder*remainder*remainder;
            originalNumber /= 10;
        }
        if (result==number)
        {
            printf("%d is a Armstrong Number",number);
        }
        number++;
        }


}

2 个答案:

答案 0 :(得分:0)

  

有人可以告诉我程序的问题吗?

问题在于result=0仅在程序开始时初始化,而result必须在每个while (number <= 500)循环周期中设置为0。

答案 1 :(得分:0)

在进入result循环之前,您忘记设置重置while(originalNumber != 0) { ... }。为防止此类容易的错误,最好在尽可能最深的块中定义变量。如果退出某个块后不必“记住”变量的内容,则可以在该块内定义变量。 (一个在{}之间的代码中的蜂鸣声)

#include <stdio.h>

/* changed `int main()` to `int main(void)` */
int main(void)
{

    for(int number = 1;  number<= 500; number++)
    {
        /*
          `number` has to be remebered each time we exit and reenter 
          this block, so we have to declare it outside.

          `orginalNumber` and `result` can be "forgot" after each time we finish
           this block so we declare them here
           (Just remember that each iteration of the loop is an "entering" and
           "exiting" of this block) 
         */  
        int originalNumber = number;
        int result = 0;

        while(originalNumber != 0)
        {
            /*
              `remainder` can be "forgot" at the end of this block, so we
               declare it here
            */ 
            int remainder= originalNumber%10;
            result += remainder*remainder*remainder;
            originalNumber /= 10;
        }
        if (result==number)
        {
            /* Added a newline when printing */
            printf("%d is a Armstrong Number\n",number);
        }
    }
}