用C编写一个程序,打印从1到10000的武器号码

时间:2016-10-10 05:33:02

标签: c

这是我写的程序。我执行它时得到一个空白输出。无法弄清楚它有什么问题。

#include <stdio.h>
void main() {
int a, b = 0, s, n;
printf("The armstrong numbers are-");
for (n = 1; n <= 10000; n++) {
  s = n;
  while (n > 0) {
    a = n % 10;
    b = b + a * a * a;
    n = n / 10;
  }
  if (b == s)
    printf("%d ", s);
}
}

3 个答案:

答案 0 :(得分:1)

正如其他人所建议的那样,不要在for循环中更改n,因为你的循环取决于变量n。每次迭代都需要将b设置回0

您的程序不太可读,因为其他人可能无法理解abns的含义。因此,请始终使用如下有意义的变量名称:(有关详细说明,请参阅注释)

#include<stdio.h>  

int main(void)      //correct signature for main function
{
    int digit;  //instead of a
    int sum=0;  //instead of b
    int number; //instead of n

    printf("The armstrong numbers are-");

    for(number = 1; number <= 10000; number++)
    { 
        int temporary = number; //temporary integer to store number value
        sum = 0;                //sum must be reset to 0 at the start of each iteration

        while(temporary > 0) 
        {
            digit = temporary % 10; 
            sum = sum + (digit * digit * digit); 
            temporary = temporary / 10;
        }

        if(sum == number)        //if sum obtained == number, print it! 
            printf("%d ",number); 
    } 

    return 0;
}

<强>输出:

The armstrong numbers are-1 153 370 371 407 

答案 1 :(得分:1)

  1. 不要在for循环中更改n。
  2. 你必须为每个n设置b回到0.
  3. 希望我帮助

答案 2 :(得分:0)

循环变量n在循环中被修改。因此,使用临时变量s来执行内部while循环。每次检查新数字时,变量b必须初始化为零。在您使用的块中定义变量是一种很好的做法,而不是全局或在main的开头定义所有内容。

#include <stdio.h>

int main() {
    int n;
    printf("The armstrong numbers are-");

    for (n=1; n<=10000; n++) {
        int a, b=0, s=n;
        while (s > 0) {
            a = s % 10;
            b = b + (a*a*a);
            s = s / 10;
        }

        if (b == n)
            printf("%d ", n);
    }
}
相关问题