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

C语言打印列表所有最高频元素的代码修复 采用命令行参数无scanf

C代码修复方案

原有代码存在的问题

  • 数组填充逻辑错误:主函数中读取命令行参数填充数组时,固定读取argv[2]的内容,导致数组所有元素都是第一个输入的数字,无法正确获取所有输入值
  • 输出逻辑不符合需求:仅打印了最高频元素的数值,没有遍历数组输出该元素的所有出现实例
  • 多余的输入提示:需求要求完全通过命令行传参,不需要打印"Enter the number of elements"这类要求输入的提示文字

修复后的完整代码

#include <stdio.h>
#include <stdlib.h>

// 找出出现频率最高的元素
int findMostFrequentElement(int A[], int n)
{
    // 冒泡排序数组
    for (int i = 0; i < n; i++)
    {    
        int temp;
        for (int j = i+1; j < n; j++) 
        {     
           if(A[i] > A[j]) 
           {    
               temp = A[i];    
               A[i] = A[j];    
               A[j] = temp;    
           }     
        }     
    }        
    // 统计最高频元素
    int max_count = 1, res = A[0], count = 1; 
    for (int i = 1; i < n; i++) { 
        if (A[i] == A[i - 1]) 
            count++; 
        else { 
            if (count > max_count) { 
                max_count = count; 
                res = A[i - 1]; 
            } 
            count = 1; 
        } 
    }   
    // 处理最后一个元素是最高频的情况
    if (count > max_count) 
    { 
        max_count = count; 
        res = A[n - 1]; 
    }   
    return res;
}

int main(int argc, char* argv[])
{
    // 第一个命令行参数是元素个数
    int n = atoi(argv[1]);
    int array[n];
    // 从第二个命令行参数开始读取数组元素
    for(int i = 0; i < n; i++)
    {
        array[i] = atoi(argv[i + 2]);
    } 
    int maxElement = findMostFrequentElement(array, n);
    // 遍历数组,打印所有等于最高频元素的实例
    for(int i = 0; i < n; i++)
    {
        if(array[i] == maxElement)
        {
            printf("%d\n", array[i]);
        }
    }
    return 0;
}

使用说明

编译后通过命令行传递参数运行即可,例如针对样例输入的运行方式:
./可执行文件名 5 3 4 6 3 3
运行后会输出三行3,完全符合预期要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 12:45:03