在习题8.8的基础上, 用一个整型数组feedback保存调查的40个反馈意见。用函数编程计算反馈意见的平均值(Mean) 、中位数(Median) 和众数(Mode) 。中位数指的是排列在数组中间的数。如果原始数据的个数是偶数,那么中位数等于中间那两个元素的算术平均值。众数是数组中出现次数最多的那个数(不考虑两个或两个以上的反馈意见出现次数相同的情况)。
输入
四十个整型
输出
平均值 中位数 众数 (double double int)
样例
标准输入复制文本 |
1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 9 |
标准输出复制文本 |
4.725000 5.000000 9 |
解题思路:
1、平均分不难求就不说了
2、中位数可以把数组升序,因为有四十个是偶数,所以(第20个数+第21个数)/2就是中位数
3、重头戏来了,如何求众数:
//求众数
int temp,max=0;
for(int i=0; i<40; i++) {
temp=0;//每次循环后自动归零
for(int j=0; j<40; j++) {
if(a[i]==a[j]) {
temp++;
}
}
if(temp>max) {
max=temp;
zhongshu=a[i];
}
}
原理就是双循环,一一比较出现相同的次数谁最多,谁就是众数~
#include <bits/stdc++.h>
using namespace std;
int main() {
int a[40];
double pingjunshu,zhongweishu,sum=0;
int zhongshu;
//求平均数
for(int i=0; i<40; i++) {
cin>>a[i];
sum+=a[i];
}
pingjunshu=sum/40.0;
//求中位数
sort(a,a+40);
zhongweishu=(a[20]+a[21])/2;
//求众数
int temp,max=0;
for(int i=0; i<40; i++) {
temp=0;//每次循环后自动归零
for(int j=0; j<40; j++) {
if(a[i]==a[j]) {
temp++;
}
}
if(temp>max) {
max=temp;
zhongshu=a[i];
}
}
printf("%.6f %.6f %d",pingjunshu,zhongweishu,zhongshu);
return 0;
}