This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center
                            
                        
                    
                
                                6年前关闭。
            
                    
在C语言中,如何计算特定元素出现在数组中的次数?然后如何向用户显示该计数?

例如,如果我有一个由{1, 2, 2, 2, 3}组成的数组。如何编写一个代码,告诉我2出现3次,然后显示给用户?

最佳答案

如果只想计算所有元素:假设数组只能包含有限范围的整数,则在第一个数组中声明另一个长度最大的数组。遍历第一个数组,并通过第一个数组增加第二个数组索引中的位置,然后打印出第二个数组。

伪代码:

 int nums[] =  {1,2,2,2,3};

 int counts[10];  // assume entries in nums are in range 0..9

 for(i = 0; i < length of nums; ++i)
 {
     num = nums[i];
     if(num < 0 or num >= length of counts)
        handle this somehow
     ++counts[num];
 }
 for(i = 0; i < length of counts; ++i)
 {
    printf("%d occurs %d times\n", i, counts[i]);
 }


如果只想计算一个特定值:

int count_in_array(int value, int* array, int length)
{
    int count = 0;
    int i;
    for(i = 0; i < length; ++i)
    {
        if(array[i] == value)
            ++count;
    }
    return count;
}

...
int nums[] =  {1,2,2,2,3};
printf("%d occurs %d times\n", 2, count_in_array(2, nums, 5));

关于c - 如何计算c中数组中的元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16620473/

10-12 14:06
查看更多