补充:中位数指的是排列在数组中间的数。如果原始数据的个数是偶数,那么中位数等于中间那两个元素的算术平均值。众数是数组中出现次数最多的那个数
#include<stdio.h>
#define N 40
//函数声明:
int Mean(int a[], int n); //int Mean(int a[], int n)(计算平均数的函数)
int Median(int a[], int n); //int Median(int a[], int n)(计算中位数的函数)
int Mode(int a[], int n); //int Mode(int a[], int n);(计算众数的函数)
void DataSort(int a[], int n); //void DataSort(int a[], int n)(获取数组元素,并排序,方便后续计算)
int main()
{
int a[N], mean, median, mode;
printf("Input the feedbacks of 40 students:\n");
DataSort(a, N);
mean = Mean(a, N);
median = Median(a, N);
mode = Mode(a, N);
printf("Mean value = %d\n", mean);
printf("Median value = %d\n", median);
printf("Mode value = %d\n", mode);
return 0;
}
void DataSort(int a[], int n)
{
int temp;
for (int i = 0; i < 40; i++) //获取元素
{
scanf("%d", &a[i]);
}
for (int i = 0; i < 40; i++) //交换法排序,方法很多,如:冒泡排序,选择排序
{
for (int j = i + 1; j < 40; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
int Mean(int a[], int n)
{
int aver = 0;
for (int i = 0; i < 40; i++)
{
aver += a[i];
}
return aver / 40;
}
int Median(int a[], int n)
{
int date;
date = a[20] + a[19];
return date / 2;
}
int Mode(int a[], int n)
{
//创建一个新的数组b[],记录每个a[i]出在数组a[N]中出现的次数
int b[40] = {0}, counter = 0, Max_number = 0, x = 0;
for (int i = 0; i < 40; i++)
{
counter = 0;
for (int j = 0; j < 40; j++)
{
if (a[i] == a[j])
counter++;
}
b[i] = counter;
}
//对比出现次数,用x保存出现次数最多下标值,函数返回a[x]
for (int i = 0; i < 40; i++)
{
if (b[i] > Max_number)
{
Max_number = b[i];
x = i;
}
}
return a[x];
}
———————————————————————————————————————————注:作者水平有限欢迎在评论区指正错误和讨论。