在C中的int数组中查找数字的频率 [英] Find frequency of digits in an int array in C

查看:103
本文介绍了在C中的int数组中查找数字的频率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数,该函数将一个数组的大小和一个由数字组成的整数数组作为输入,并打印每个数字的频率。

I am trying to write a function that takes the size of an array and an int array made up of digits as input and prints the frequency of each digit.

样本输入和输出:

Input: [1,2,2,3,3,3]

Output:
1 occurs 1 times.
2 occurs 2 times
3 occurs 3 times.

这是我的尝试(不是最优雅的方法):

Here is my attempt (not the most elegant):

void freq(int size, int numArray[]) {
    int one=0, two=0, thr=0, fou=0, fiv=0, six=0, sev=0, eit=0, nin=0;
    int i, j;

    for (i = 0; i < size; i++) {
        for (j = 1; j < size; j++) {
            if (numArray[i] == numArray[j] && numArray[i] == 1) {
                one+=1;
            }
            else if (numArray[i] == numArray[j] && numArray[i] == 2) {
                two+=1;
            }
            else if (numArray[i] == numArray[j] && numArray[i] == 3) {
                thr+=1;
            }
            else if (numArray[i] == numArray[j] && numArray[i] == 4) {
                fou+=1;
            }
            else if (numArray[i] == numArray[j] && numArray[i] == 5) {
                fiv+=1;
            }
            else if (numArray[i] == numArray[j] && numArray[i] == 6) {
                six+=1;
            }
            else if (numArray[i] == numArray[j] && numArray[i] == 7) {
                sev+=1;
            }
            else if (numArray[i] == numArray[j] && numArray[i] == 8) {
                eit+=1;
            }
            else if (numArray[i] == numArray[j] && numArray[i] == 9) {
                nin+=1;
            }
        }
    }
    printf("1 occurs %d times.\n", one);
    printf("2 occurs %d times.\n", two);
    printf("3 occurs %d times.\n", thr);
    printf("4 occurs %d times.\n", fou);
    printf("5 occurs %d times.\n", fiv);
    printf("6 occurs %d times.\n", six);
    printf("7 occurs %d times.\n", sev);
    printf("8 occurs %d times.\n", eit);
    printf("9 occurs %d times.\n", nin);
}

这有问题。如果使用上面的示例,这就是我得到的:

This has problems. If I use the same example as above, this is what I get:

Input: [1,2,2,3,3,3]

Output:
1 occurs 0 times.
2 occurs 4 times.
3 occurs 9 times.


推荐答案

嵌套循环方法没有任何意义,您只需要一次查看每个数字进行计数。当然,保留数组更有意义:

The nested loop approach makes no sense, you only need to look at each digit once to count it. And of course an array makes more sense to keep the counters:

void freq(int size, const int *numbers)
{
  unsigned int counts[10] = { 0 };
  for(int i = 0; i < size; ++i)
  {
    const int here = numbers[i];
    if(here >= 1 && here <= 9)
      counts[here]++;
  }
  for(int i = 1; i < 10; ++i)
    printf("%d occurs %u times\n", i, counts[i]);
}

这篇关于在C中的int数组中查找数字的频率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆