C语言统计数组里面各个元素出现的次数

#include <iostream>
#include<stdio.h>




int main() {

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

    int size = sizeof(nums) / sizeof(nums[0]);

    // 创建一个全0的空数组

    int* counterNums = (int*)calloc( size, sizeof(int));

    
    for (int i = 0; i < size; i++) {

        counterNums[nums[i]]++; // 再counterNums下标等于nums里面的元素的位置, 将其复制+1,每遇到一次就+1
    }

    for (int i = 0; i < size; i++) {
        printf("%d  ", counterNums[i]);
    }


    // get the counter of 2
    printf("\n2 counter is %d\n", nums[2]);

    return 0;
}

 

posted @ 2023-09-25 14:48  朵朵奇fa  阅读(300)  评论(0编辑  收藏  举报