为什么这个程序的输出是错误的?

时间:2019-01-02 14:04:30

标签: 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 个答案:

答案 0 :(得分:0)

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