#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;
}
}
查找众数及中位数(C++)
最新推荐文章于 2025-11-11 00:15:00 发布
1178

被折叠的 条评论
为什么被折叠?



