问题:如何确定一个数是否为阿姆斯特朗数

3
我正在尝试检查用户提供的数字是否为阿姆斯特朗数。但是出现了问题,我无法解决。
感谢任何帮助。
以下附上代码。
#include<stdio.h>

int fun(int);

int main()
{
    int x,a,b,y=0;

    printf("enter the number you want to identify is aN ARMSTRONG OR NOT:");
    scanf("%d",&a);

    for(int i=1 ; i<=3 ; i++)
    {
        b = a % 10;
        x = fun(b);
        y = x+y;
        a = a/10;
    }

    if(y==a)
        printf("\narmstrong number");
    else
        printf("\nnot an armstrong number");

    return 0;
}

int fun(int x)
{
    int a;
    a=x*x*x;
    return (a);
}

@ash burlaczenko:它没有正确地给出输出,因为153是阿姆斯特朗数,我想要检查这个数,但是根据上面的代码,它并不是一个阿姆斯特朗数,这里有什么问题吗? - nobalG
1
@阿尔弗雷德·诺贝尔 一个问题可能是你正在改变 a (所以它将不再有原始值)。还有所有的炸药东西。 - cnicutar
2
只有有限数量的阿姆斯特朗数,所以最好创建一个查找表:D - user616736
1
@Alfred,这段代码有很多问题,回答它们会很有趣。希望它能重新打开。 - Johan
fun()?,哈哈!那让我微笑了。 - Stephane Gosselin
显示剩余6条评论
9个回答

3
主要问题是您没有记录起始数字的数量。 您反复将 a 除以 10(最终结果为0),然后将0与153进行比较。 这些不相等。
您的另一个问题是无法查找四位数或更长的阿姆斯特朗数,也无法查找1以外的1位数字。 您的函数fun()最好被重命名为cube(); 在下面的代码中,它被重命名为power(),因为它被推广为处理N位数。
我决定,在考虑幂级别范围内,没有必要使用更复杂的算法来处理power() - 即除以二等。 对于6-10位数字,可以节省空间,但在这种情况下无法测量。 如果使用-DDEBUG编译,则包括诊断打印 - 它用于向我保证我的代码正常工作。 还请注意,答案回显输入。 这是确保您获得正确行为的基本技术。 我将代码封装成一个函数,以测试数字是否为阿姆斯特朗数,并从主程序迭代调用该函数。 这使得测试变得更加容易。 我已经检查了大多数阿姆斯特朗数,最高到146511208,结果似乎是正确的。 370和371这对数字很有趣。
#include <stdio.h>
#include <stdbool.h>

#ifndef DEBUG
#define DEBUG 0
#endif

static int power(int x, int n)
{
    int r = 1;
    int c = n;
    while (c-- > 0)
        r *= x;
    if (DEBUG) printf("    %d**%d = %d\n", x, n, r);
    return r;
}

static bool isArmstrongNumber(int n)
{
    int y = 0;
    int a = n;
    int p;
    for (p = 0; a != 0; a /= 10, p++)
        ;
    if (DEBUG) printf("    n = %d, p = %d\n", n, p);
    a = n;
    for (int i = 0; i < p; i++)
    {
        y += power(a % 10, p);
        a /= 10;
    }
    return(y == n);
}

int main(void)
{
    while (1)
    {
        int a;
        printf("Enter the number you want to identify as an Armstrong number or not: ");
        if (scanf("%d", &a) != 1 || a <= 0)
            break;
        else if (isArmstrongNumber(a))
            printf("%d is an Armstrong number\n", a);
        else
            printf("%d is not an Armstrong number\n", a);
    }

    return 0;
}

@Johnathan,+1,但是所有 ap 变量是怎么回事?我知道这只是一些琐碎的代码,但有意义的变量名有什么问题吗? - Johan
1
@Johan;原始代码中有它们,我认为没有必要改变。在琐碎的代码中,我倾向于使用单个字母名称。如果是我的话,我可能会花更多时间来命名 - 但不一定需要太多。(ysum,也许; pndigits,也许; anumber,也许。我不会改变 in。我不会改变 power() 中的变量 - 缺少的单行注释就足够了。在 main() 中,我可能会使用 number 而不是 a(因为当我学习编程时,a 隐含着一个 REAL*4 - Fortran!)。 - Jonathan Leffler
@Johan:我可能会重写power(),使用for (int i = 0; i < n; i++)循环。我很少使用倒计数循环,最初使用它的原因是因为我倒数的是n而不是c,但这使得调试打印不准确。回想起来,一旦更改被保留n,我应该做得更彻底。 - Jonathan Leffler

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

int power(int, int);
int numberofdigits(int);

//Routine to test if input is an armstrong number.
//See: http://en.wikipedia.org/wiki/Narcissistic_number if you don't know
//what that is. 

int main()
{
    int input;
    int digit;
    int sumofdigits = 0;

    printf("enter the number you want to identify as an Armstrong or not:");
    scanf("%d",&input);

    int candidate = input;
    int digitcount = numberofdigits(input);

    for(int i=1 ; i <= digitcount ; i++) 
    {
        digit = candidate % 10;
        sumofdigits = sumofdigits + power(digit, digitcount);
        candidate = candidate / 10;
    }

    if(sumofdigits == input)
        printf("\n %d is an Armstrong number", input);
    else
        printf("\n %d is NOT an Armstrong number", input);
    return 0;
}

int numberofdigits(int n);
{
  return log10(n) + 1;
}

int power(int n, int pow)
{
  int result = n;
  int i=1;
  while (i < pow) 
  {
    result = result * n; 
    i++;
  }
}

代码有什么问题:

  1. 没有使用有意义的变量名,使得代码的含义难以理解;记住,代码是为人类而非编译器编写的。
  2. 不要使用令人困惑的代码,例如: int x,a,b,y=0;,这很令人困惑,所有变量都被设置为0还是只有y?请将初始化变量的变量放在单独的一行上,这样阅读会更容易。尽最大努力消除歧义,长远来看这将会带来巨大的回报。
  3. 使用注释:如果你不知道什么是阿姆斯特朗数,那么从你的代码中很难看出来。请加入一些有意义的注释,让人们知道你的代码应该做什么。这将使你和他人更容易理解,因为他们知道你的意图并且可以看到你实际做了什么,并在需要时解决差异。
  4. 使用有意义的函数名 fun(x)是什么鬼?永远不要给任何东西命名为fun(),这就像没有事实的科学,何意义?
  5. 不要硬编码,你的程序只接受阿姆斯特朗3位数,但如果可以硬编码,为什么不这样做:return (input == 153) || (input == 370) || ....

我明白了。根据你的代码,我在改变输入变量,这就是我的错误所在。 - nobalG
1
正如@Jonathan Lefflers的评论所说,此代码仅适用于3位数。根据链接中阿姆斯特朗数的定义,您需要将其乘以(数字位数)的幂。 - user681007
(续)您没有修复提示消息中的特殊大写。您没有显示#include <math.h>,但您使用了log10()。我观察到您没有将测试代码重构为函数——虽然这不是很值得批评,但它有助于代码的可测试性。还有其他一些可以批评的小布局细节。 - Jonathan Leffler
@Johan:仅供记录,我们两个人的名字都只有一个 'h'。此外,由于你拼错了我的名字,我没有收到评论的报告(前三个字符必须匹配)。 - Jonathan Leffler
@用户,下次我会使用C++。 - Johan
显示剩余2条评论

2

可能存在一个问题,那就是你正在改变a(因此它将不再具有原始值)。此外,它只能匹配1、153、370、371、407。这是一个提示,可以替换for循环并测试,直到a为零,并将函数更改为提高到数字的位数。


3
实际上,它不会匹配2到9,因为它对它们进行了立方运算。它识别1是因为1的立方也是1。 - Jonathan Leffler

1

好的,事情是这样的,存在一些阿姆斯特朗数不仅仅是3位数,例如1634、8208是4位数的阿姆斯特朗数,54748、92727、93084等为5位数的阿姆斯特朗数,以此类推。因此,要检查一个数字是否是阿姆斯特朗数,我做了以下操作。

#include <stdio.h>

int main()
{
    int a,b,c,i=0,sum=0;

    printf("Enter the number to check is an Armstrong number or not :");
    scanf("%d",&a);
    
    //checking the digits of the number.
    b=a;
    while(b!=0)
    {
        b=b/10;
        i++;
    }
    // i indicates the digits

    b=a;
    while(a!=0)
    {
        int pwr = 1;
        c= a%10;

        //taking mod to get unit place and getting its nth power of their digits    

        for(int j=0; j<i; j++)
        {
            pwr = pwr*c;
        }

        //Adding the nth power of the unit place

        sum += pwr;
        a = a/10;
        //Dividing the number to give the end condition
    }

    if(sum==b)
    {
        printf("The number %d is an Armstrong number",b);
    }
    else
    {
        printf("The number %d is not an Armstrong number",b);
    }
}

0

这里有一种方法可以检查一个数字是否为阿姆斯特朗数

t=int(input("nos of test cases"))
while t>0:
    num=int(input("enter any number = "))
    n=num
    sum=0
    while n>0:
        digit=n%10
        sum += digit ** 3
        n=n//10

    if num==sum:
        print("armstronng num")
    else:
        print("not armstrong")
    t-=1

0
/* 
Name: Rakesh Kusuma

Email Id:  rockykusuma@gmail.com

Title: Program to Display List of Armstrong Numbers in 'C' Language

*/



#include<stdio.h>

#include<math.h>

int main()

{

int temp,rem, val,max,temp1,count;

int num;

val=0;

num=1;

printf("What is the maximum limit of Armstrong Number Required: ");

scanf("%d",&max);

printf("\nSo the list of Armstrong Numbers Before the number %d are: \n",max);

while(num <=max)

    {         
        count = 0;

        temp1 = num;

        while(temp1!=0)

        {
            temp1=temp1/10;

            count++;
        }   

        if(count<3)

        count = 3;

            temp = num;

            val = 0;

            while(temp>0)

            {

                rem = temp%10;

                val = val+pow(rem,count);

                temp = temp/10;

            }

            if(val==num)

            {

                printf("\n%d", num);

            }

     num++; 

    }

 return 0;

 }

这将适用于任何数字...只需给出数字的最大限制即可。它将显示在1和给定的最大限制数字之间的所有阿姆斯特朗数..谢谢 - Rakesh Kusuma

0

使用C语言检查数字是否为阿姆斯特朗数

#include<stdio.h>
#include<conio.h>
void main()
{
    A:
    int n,n1,rem,ans;
    clrscr();
    printf("\nEnter No. :: ");
    scanf("%d",&n);

    n1=n;
    ans=0;
    while(n>0)
    {
        rem=n%10;
        ans=ans+(rem*rem*rem);
        n=n/10;
    }

    if(n1==ans)
    {
        printf("\n Your Entered No. is Armstrong...");
    }
    else
    {
        printf("\n Your Entered No. is not Armstrong...");
    }

    printf("\n\nPress 0 to Continue...");
    if(getch()=='0')
    {
        goto A;
    }
    printf("\n\n\tThank You...");
    getch();
}

请注意,仅包含代码的答案可能会被删除,除非它们有非常好的注释来解释它们正在做什么。 - Wai Ha Lee

0

如果你正在尝试寻找阿姆斯特朗数,那么你发布的解决方案缺少一个情况,即当你的数字大于3时...阿姆斯特朗数可以大于3位数(例如9474)。这是Python代码,逻辑很简单,可以转换为任何其他语言。

def check_armstrong(number):
    num = str(number)
    total=0
    for n in range(len(num)):
        total+=sum(int(num[n]),len(num))       

    if (number == total):
        print("we have armstrong #",total)

def sum(input,power):
    input = input**power
    return input

check_armstrong(9474)

-1

这是我曾经编写和看到的最简单的阿姆斯特朗数检测代码:

def is_Armstrong(y):
    if y == 0:
        print('this is 0')
    else:
        x = str(y)
        i = 0
        num = 0
        while i<len(x):
            num += int(x[i])**(len(x))
            i += 1
            if num == y:
                print('{} is an Armstrong number.'.format(num))
                break
            else:
                print('{} is not an Armstrong number.'. format(y))
is_Armstrong(1634)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接