阿姆斯特朗号的C程序输出不正确

时间:2015-09-24 16:38:40

标签: c

这个程序有什么问题。它编译但没有给出正确的输出。

/* Program for Armstrong Number*/

#include<stdio.h>
#include<math.h>

void main()
{
        int num,sum=0,temp,d;
        printf("\n========Program for Armstrong Number=========\n");
        printf("Enter the number        :       ");
        scanf("%d",&num);
        temp=num;
        while(temp>10){
                d=temp%10;
                sum+=pow(d,3);
                d/=10;
        }
        sum+=pow(temp,3);

        if(sum==num)
                printf("\nThe number %d is an Armstrong Number\n",num);
        else
                printf("\nThe number %d is not an armstrong number\n",num);
}

3 个答案:

答案 0 :(得分:0)

   while(temp>10){
            d=temp%10;
            sum+=pow(d,3);
            d/=10;             // this should be temp/=10;
       }

这个循环是无限的,因为你不能修改temp

答案 1 :(得分:0)

d/=10;更改为temp/=10;

检查代码

#include<stdio.h>
#include<math.h>

 int main()
{
    int num,sum=0,temp,d;
    printf("\n========Program for Armstrong Number=========\n");
    printf("Enter the number        :       ");
    scanf("%d",&num);
    temp=num;
    while(temp>10){
            d=temp%10;
            sum+=pow(d,3);
            temp/=10;
    }
    sum+=pow(temp,3);

    if(sum==num)
            printf("\nThe number %d is an Armstrong Number\n",num);
    else
            printf("\nThe number %d is not an armstrong number\n",num);
 }

答案 2 :(得分:0)

除了已经指出的while循环中的错误之外,您的程序正在对数字的多维数据集求和。阿姆斯壮的数字是 n 数字,它等于各个数字的 nth 幂之和。以下内容来自维基百科:

  

在娱乐数论中,自恋数字(也称为完美数字不变量(PPDI),阿姆斯特朗数字(在迈克尔·阿姆斯特朗之后)或加号完美数字)是一个数字,它是自己的数字的总和每个都提升到数字位数。

因此,如果您想测试我理解为阿姆斯壮的数字,您首先需要计算数字,以了解将数字提升到什么样的数字。以下是您修改后的代码:

#include<stdio.h>
#include<math.h>

void main()
{
  int num, sum = 0, temp, d;
  int digits = 0; // Added variable to count digits
  printf("\n========Program for Armstrong Number=========\n");
  printf("Enter the number        :       ");
  scanf("%d", &num);

  // Count the number of digits
  temp = num;
  while (temp != 0){
    digits++;
    temp = temp / 10;
  }

  temp = num;
  while (temp != 0){
    d = temp % 10;
    sum += pow(d, digits);
    temp /= 10; // This was d /= 10;
  }

  if (sum == num)
    printf("\nThe number %d is an Armstrong Number\n", num);
  else
    printf("\nThe number %d is not an armstrong number\n", num);
} 

如果您只是想测试数字是否等于各个数字的多维数据集的总和,那么只需修复while循环。

相关问题