c - 为什么这个程序的输出是错误的?.数字的频率

标签 c

数字频率的程序
请帮助我编写此代码以获得清晰的输出。我是初学者 我已经使用数组编写了该程序。我不知道这是否正确。用我自己的逻辑制作

int count(int a)  
{  
    int c;    
    while(a>=1)  
    {  
        c++;  
        a=a/10;  
    }  
    return c;  
}
int main()   
{  
     //program to find frquency of the number  
     int a,n,d;  
     int b[100];  
     int e[100];  
     scanf("%d",&a);
     n=count(a);

     for(int i=n;a>0;i--)     
     {
        b[i]=a%10; 
        a=a/10;
     }
     for(int i=1;i<=n;i++) 
     {

        d=b[i];
        e[d]++;//most probably this part error occurs
        printf("%d\n",d); //used this this to confirm that i have correctly stored value in d.
     }

      for(int i=1;i<=n;i++) 
     {

        printf("%d ",e[i]);
     }

    return 0;
}

最佳答案

  1. int c; 应为 int c = 0;
  2. int e[100]; 应为 int e[100] = {0};

以下代码可以工作:

#include <stdio.h>

int count(int a) {
  int c = 0;
  while (a >= 1) {
    c++;
    a = a / 10;
  }
  return c;
}
int main() {
  // program to find frquency of the number
  int a, n, d;
  int b[100];
  int e[100] = {0};
  scanf("%d", &a);
  n = count(a);

  for (int i = n; a > 0; i--) {
    b[i] = a % 10;
    a = a / 10;
  }
  for (int i = 1; i <= n; i++) {
    d = b[i];
    e[d]++;             // most probably this part error occurs
    printf("%d\n", d);  // used this this to confirm that i have correctly
                        // stored value in d.
  }

  for (int i = 1; i <= n; i++) {
    printf("%d ", e[i]);
  }

  return 0;
}

此外,您还可以使用 snprintf 来实现:

    #include <stdio.h>

    int main() {
      int a;
      int max = -1;
      char buf[100];
      int count[10] = {0};

      scanf("%d", &a);
      snprintf(buf, sizeof(buf), "%d", a);

      for (int i = 0; buf[i] != '\0'; ++i) {
        int temp = buf[i] - '0';
        ++count[temp];
        if (temp > max)
          max = temp;
      }

      for (int i = 0; i <= max; ++i)
        printf("%d ", count[i]);

      return 0;
    }

关于c - 为什么这个程序的输出是错误的?.数字的频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54007736/

相关文章:

c - C中的链表删除函数问题

c - 如何在不使用 POSIX 库 <pthread.h> 的情况下在 C 中创建线程

C 程序从 .txt 文件获取每行的第一个单词并将该单词打印到另一个 .txt 文件 : Kind of works but also prints random letters

c - 我如何知道 C 程序的可执行文件是在前台还是后台运行?

ios - 如何在 Swift 中使用 SCNetworkReachability

c - 错误: "lvalue required as left operand of assignment"

c - 以编程方式检索 C 结构成员的内存偏移量,无需硬编码成员名称

c - 如何在 C 语言中对数字数组进行排序而不将它们移动?

c - 是否可以使用用户输入设置常量?

java - 机器人 JNI : app stops working