加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 确定数字是否为阿姆斯壮数的问题

发布时间:2020-12-16 09:35:05 所属栏目:百科 来源:网络整理
导读:我正在尝试检查用户提供的号码是否为 armstrong number.虽然有些问题但我无法理解. 任何帮助表示赞赏. 代码见下文. #includestdio.hint fun(int);int main(){ int x,a,b,y=0; printf("enter the number you want to identify is aN ARMSTRONG OR NOT:"); sca
我正在尝试检查用户提供的号码是否为 armstrong number.虽然有些问题但我无法理解.

任何帮助表示赞赏.

代码见下文.

#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);
}

解决方法

主要问题是您没有记录您开始使用的号码.你将a重复除以10(结束为0),然后将0与153进行比较.这些不相等.

你的另一个问题是,你不能寻找4位数或更长的阿姆斯特朗数字,也不能寻找除1之外的1位数字.你的函数fun()会更好地命名为cube();在我的下面的代码中,它被重命名为power(),因为它被推广为处理N位数字.

我决定,对于所考虑的功率范围,没有必要使用更复杂的power()算法 – 一个除以2等等.可以节省6-10位数,但你不能’在这种情况下衡量它.如果用-DDEBUG编译,它包括诊断打印 – 用于向我保证我的代码工作正常.还要注意答案回应输入;这是确保您获得正确行为的基本技术.我已经将代码包装成一个函数来测试一个数字是否是一个阿姆斯特朗数,这是从主程序迭代调用的.这使得测试更容易.我已将检查添加到scanf()以阻止问题,这是另一项重要的基本编程技术.

我检查了大部分阿姆斯特朗的数字,最高可达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 = %dn",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 = %dn",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 numbern",a);
        else
            printf("%d is not an Armstrong numbern",a);
    }

    return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读