查找众数及中位数(C++)

#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;

//寻找众数和中位数
struct nc{
    int num;
    int count;
};

bool compare(const nc& a, const nc& b){
    if(a.count != b.count){
        return a.count > b.count;
    }
    else{
        return a.num < b.num;
    }
}

int main() {
    map<int, int> num_count;//记录数字的次数
    int num;
    while(cin >> num){
        num_count[num]++;
    }
    vector<nc> max_count;//记录数字和数字出现的次数
    for(auto it : num_count){
        max_count.push_back({it.first, it.second});
    }
    //按照出现次数进行排列
    sort(max_count.begin(), max_count.end(), compare);
    int max_c = max_count[0].count;//最多出现次数
    vector<int> arr;//记录众数的数组
    int index = 0;
    while(max_count[index].count == max_c){
        arr.push_back(max_count[index].num);
        index++;
    }
    double mid;
    if(arr.size()%2 == 0){//arr.size()是偶数
        int r = arr.size()/2;
        mid = (double)(arr[r]+arr[r - 1])/2;
        printf("%.2f\n", mid);
    }
    else{
        mid = (arr[arr.size()/2]);
        cout << mid << endl;
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值