c - 识别阿姆斯特朗数

标签 c

我编写了这段代码,可以识别一个数字是否是阿姆斯特朗数字

 #include <stdio.h>
    #include <stdlib.h>
     int n;
    const int input()
    {
        printf("insert n:");
        scanf("%d",&n);
        return n;
    }   
    int Num_amount()
    {
      int amount=0;
      while(n>=10)
      {
          amount++;
          n=n/10;
          if(n<10)
            amount++;
      }
      return amount;
    }
    int Armstrong()
    {
        n=input();
        int v;
        int z=0;
        int y=10
      int x=Num_amount();
      int m[100]={};
      int i;
      for(i=0;n>=10;i++)
      {
          v=n%10;
        m[i]=pow(v,x);
        z=z+m[i];
        y=y*10;
      }
      return z;
    }
    int main()
    {
    int z=Armstrong();
    printf("%d",z);
    }

当使用n=153运行时,我总是得到0。经过多次调试,我发现问题出在Armstrong函数中的某个地方(最有可能)

 int Armstrong()
            {
                n=input();
                int v;
                int z=0;
                int y=10
              int x=Num_amount();
              int m[100]={};
              int i;
              for(i=0;n>=10;i++)
              {
                  v=n%10;
                m[i]=pow(v,x);
                z=z+m[i];
                y=y*10;
              }
              return z;
        }

调试 watch 表明,它没有执行for循环,而是直接进入return z行,我已经尝试了所有方法,但仍然无法弄清楚.你能告诉我问题是什么吗?

最佳答案

由于某些逻辑错误,您得到了错误的结果。当您选择一个全局变量时,您需要考虑该变量值可以被任何函数修改,在这种情况下,您已经在num_amount 函数。您还在 Num_amountArmstrong 函数中犯了一些逻辑错误。 您尚未包含 powmath.h 头文件。

这是您修改后的代码,

    #include <stdio.h>
    #include <stdlib.h>
    #include<math.h>    //<-------------Should have included 

         int n;
    const int input()
    {
        printf("insert n:");
        scanf("%d",&n);
        return n;
    }  

    int Num_amount()       //<------------modified 
    {
        int z = n;        //<--------take a copy of global n
      int amount=0;
      while(z>0)
      {
          amount++;
          z=z/10;
      }
      return amount;
    }
    int Armstrong()         //<------------modified 
    {
        n=input();
        int v;
        int z=0;
      int x=Num_amount();
      int i;
      while(n>0)
      {
          v=n%10;
          z+=pow(v,x);
          n/=10;         //<-------modification of global n
      }
      return z;
    }


    int main()
    {
    int z=Armstrong();
    printf("%d",z);
    }

关于c - 识别阿姆斯特朗数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52950508/

相关文章:

C函数指针行为,数组/数组指针行为

我可以通过复制函数指针指向的数据来移动 C 中的函数吗?

c - 如何为静态嵌入式操作系统中的资源创建复杂的宏检查?

C printf 术语进度显示,并在下一行显示错误消息

c - 下面的代码是什么意思/做什么?

c - c 中的 IF 或 boolean 语句

c - 使用一个 for 循环就地转置矩阵

c - C 中的二进制搜索无法正常工作

c - 字符串文字导致小内存泄漏?

c++ - 二维数组中指针衰减后的大小