首页 > 解决方案 > 为什么这个程序的输出是错误的?。数字的频率

问题描述

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

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

标签: c

解决方案


  1. 该行int c;应该是int c = 0;
  2. 该行int e[100];应该是int e[100] = {0};

以下code可以工作:

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

推荐阅读