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

C++统计数组最高频元素输出异常如何解决

现有代码问题梳理

  • 缺失依赖头文件:使用unordered_map需要提前引入<unordered_map>头文件,否则会编译报错
  • 变量未定义:代码中用到的input_number没有提前声明、赋值,无法正常运行
  • 核心逻辑不符合需求:末尾的循环是遍历所有输入的数字,输出每个数字对应的出现次数,这就是你输入1、1、1、2时输出3、3、3、1的直接原因
  • 类型不匹配:存储输入的vector用了double类型,但统计频率的unordered_map键为int类型,存在隐式类型转换的潜在风险

修复后的代码

#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;

int main()
{
    int input_number;
    cout << "请输入要统计的数字总个数:" << endl;
    cin >> input_number;
    vector<int> numbers(input_number);

    cout << "输入0到50范围内的数字:" << endl;
    for (int i = 0; i < input_number; ++i) {
        cin >> numbers[i];
    }
    unordered_map<int, int> freq;
    for (int i = 0; i < numbers.size(); i++) {
        freq[numbers[i]]++;
    }

    // 遍历频率表找出现次数最多的数字
    int max_count = 0;
    int res_num = 0;
    for (auto& pair : freq) {
        if (pair.second > max_count) {
            max_count = pair.second;
            res_num = pair.first;
        }
    }
    cout << res_num << endl;

    return 0;
}

修复说明

  • 补充了<unordered_map>头文件,新增了input_number的输入逻辑,解决编译问题
  • 把存储输入的vector类型改为int,和频率表键类型统一,避免类型转换问题
  • 新增了遍历频率表找最高频数字的逻辑,直接输出最终结果,符合需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 03:36:03