题目描述
输入一个整型数组,要求第一行输入数组元素数量,第二行输入数组元素,每个元素之间用空格分离。
6
12 3 5 17 9 8
输出数组的中位数,若中位数不是整数,则保留一位小数。
8.5
参考步骤
- 输入数据;
- 排序数组;
- 求中位数;
参考代码
// I: First line, input number of elements in arrary;
// I: Second line, input array, dividing with space;
// O: The Medians, if not an integer, then keep one decimal.
#include <stdio.h>
int main (){
// input array
int numbers, e; //initialize array
scanf("%d", &numbers);
int sorting_list[numbers];
for (e = 0; e < numbers; e++){
scanf("%d", &sorting_list[e]);
}
输入数组。
// sort array
int bucket; //switcher
int i, j; // iterators
int list_length = sizeof(sorting_list) / 4 ; //get length of array;
for (i = 0; i < list_length - 1; i++){ // set times of moving elements;
for (j = 0; j < list_length-1; j++){ // per loop, move n-1 couples of integers;
if (sorting_list[j] < sorting_list[j+1]){
bucket = sorting_list[j]; //from big to small;
sorting_list[j] = sorting_list[j+1];
sorting_list[j+1] = bucket; // switch 2 elements;
}
else continue;
}
}
//int m;
//for (m=0; m< list_length; m++) printf("%d\n", sorting_list[m]);
排序
这里使用了sizeof()
函数来计算数组元素个数。
其机制是,sizeof()
可以返回某个变量的占用字节数(Byte),而常见编译器会为整型数据分配4个字节空间,又因为数组的元素在内存中连续存储,故利用 sizeof(数组)/4
可以求出数组长度。
sizeof()
的数据类型是lu
,即long unsigned
。
// find median
if (list_length % 2 == 0 ){ // number of array is EVEN.
double m2 = sorting_list[list_length/2];
double m1 = sorting_list[list_length/2 - 1]; // Caution, indice start from 0;
if ((sorting_list[list_length/2] + sorting_list[list_length/2 -1]) % 2 == 0){ // mean is even, median should be a integer.
printf("%.0lf\n", (m1+m2)/2);
}
else printf("%.1lf\n", (m1+m2)/2);
}
else { // amount of array elements is ODD.
printf("%d\n", sorting_list[list_length/2]);
}
return 0;
}
求中位数。