You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何打印数组中所有重复元素及其重复次数

解决方案

要实现自动输出数组中所有重复元素及其次数,核心是遍历数组统计每个元素的出现次数,同时避免重复统计同一元素。以下是修改后的代码:

#include <stdio.h>

int main() {
    int arr[] = {1, 4, 5, 9, 7, 1, 8, 1, 5};
    int arr_len = sizeof(arr) / sizeof(arr[0]);
    // 标记数组:记录元素是否已统计,避免重复输出
    int counted[arr_len];
    // 初始化标记数组为0(未统计状态)
    for (int i = 0; i < arr_len; i++) {
        counted[i] = 0;
    }

    printf("The duplicates are ");
    int first_output = 1; // 控制逗号输出,第一个元素前不打印逗号

    for (int i = 0; i < arr_len; i++) {
        if (counted[i] == 1) {
            continue; // 已统计过的元素直接跳过
        }

        int count = 0;
        // 统计当前元素的出现次数,同时标记所有相同元素为已统计
        for (int j = 0; j < arr_len; j++) {
            if (arr[i] == arr[j]) {
                count++;
                counted[j] = 1;
            }
        }

        // 仅输出出现次数≥2的重复元素
        if (count >= 2) {
            if (!first_output) {
                printf(" , ");
            }
            printf("%d:%d", arr[i], count);
            first_output = 0;
        }
    }
    printf("\n");
    return 0;
}

关键说明:

  • 自动适配数组长度:用sizeof(arr)/sizeof(arr[0])替代硬编码的数组长度,让程序兼容任意长度的数组。
  • 避免重复统计:通过counted数组标记已处理过的元素,防止同一个重复元素被多次输出。
  • 格式规范:用first_output变量控制逗号的输出时机,保证输出格式和示例一致(无开头多余逗号)。

运行结果:

针对给定数组{1,4,5,9,7,1,8,1,5},程序输出:

The duplicates are 1:3 , 5:2

内容的提问来源于stack exchange,提问作者Jane

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 02:50:51