阿姆斯特朗数字的代码不起作用

Code for Armstrong numbers not working

本文关键字:不起作用 代码 数字 阿姆斯特朗      更新时间:2023-10-16

好吧,请放轻松。只是学习C++,首先在这里提问。我写了一个程序来列出所有低于1000的阿姆斯特朗数字。虽然我已经阅读了维基百科关于自恋数字的文章,但我只在寻找 3 位数的数字。这意味着我只关心数字立体的总和。

它的工作原理是执行 1 到 1000 的 for 循环,使用用户定义的函数检查索引变量是否为 armstrong,如果是,则打印它。用户定义的函数只需使用 while 循环来隔离数字并将立方体的总和与原始数字匹配即可。如果为 true,则返回 1,否则返回 0。

问题是,我在输出中得到的绝对没有数字。只有 void main() 中的 cout 语句出现,其余的为空。试图尽可能多地调试。Complier是Turbo C++。法典-

#include<iostream.h>
#include<conio.h>
int chk_as(int);//check_armstrong
void main()
{
    clrscr();
    cout<<"All Armstrong numbers below 1000 are:n";
    for(int i=1;i<=1000;i++)
    {
        if (chk_as(i)==1)
            cout<<i<<endl;
    }
    getch();
}
int chk_as (int n)
{
    int dgt;
    int sum=0,det=0;//determinant
    while (n!=0)
    {
        dgt=n%10;
        n=n/10;
        sum+=(dgt*dgt*dgt);
    }
    if (sum==n)
    {det=1;}
    else
    {det=0;}
    return det; 
}

问题是您正在动态更改方法中 n 的值,但您需要其原始值来检查结果。

添加一个临时变量,例如 t。

int t = n;
while (t!=0)
{
    dgt=t%10;
    t=t/10;
    sum+=(dgt*dgt*dgt);
}
if (sum==n)
// ... etc.

编辑:没关系...这是错误的

while (n!=0)
    {
    dgt=n%10;
    n=n/10;
    sum+=(dgt*dgt*dgt);
    }

这将永远运行,因为n永远不会达到 0。

问题是,在循环的末尾

while (n!=0)
{
    dgt=n%10;
    n=n/10;
    sum+=(dgt*dgt*dgt);
}

n 为 0,因此条件if (sum==n)永远不会为真。

尝试类似以下内容:

int chk_as (int n)
{
int copy = n;
int dgt;
int sum=0,det=0;//determinant
while (copy!=0)
    {
    dgt=copy%10;
    copy=copy/10;
    sum+=(dgt*dgt*dgt);
    }
if (sum==n)
{det=1;}
else
{det=0;}
return det; 
}

我在这里给出了查找三位数字的阿姆斯特朗数的程序。

阿姆斯特朗数的条件是,其数字的立方体之和必须等于数字本身。

例如,407 作为输入给出。4 * 4 * 4 + 0 * 0 * 0 + 7 * 7 * 7 = 407 是一个阿姆斯特朗数。

#include <stdio.h>
int main()
{
      int i, a, b, c, d;
      printf("List of Armstrong Numbers between (100 - 999):n");
      for(i = 100; i <= 999; i++)
      {
            a = i / 100;
            b = (i - a * 100) / 10;
            c = (i - a * 100 - b * 10);
            d = a*a*a + b*b*b + c*c*c;
            if(i == d)
            {
                  printf("%dn", i);
            }
      }  
      return 0;
}

介于 (100 - 999) 之间的阿姆斯壮数列表:153370371407

参考: http://www.softwareandfinance.com/Turbo_C/Find_Armstrong_Number.html