Problem Description
给定一个由N个非负整数构成的序列,我们来定义一下序列的中位数,如果N是奇数,在对序列排序后,中位数就是最中间的那个数,即排序后,中位数的位置为(N+1)/2,这里序列的位置从1开始。如果N是偶数,则中位数为排序后中间两个数和的一半,即N/2和(N/2)+1处。但是需要注意的是原始序列可能是未排序的。
你的任务就是编程找出给定序列中的中位数。
Input
第一行只有一个整数N,表示序列的长度。接下来就是N个数,每个数占一行,序列的长度范围为1到250000。序列中的每个数都是不超过2^32 – 1(包括它)的正整数。
Output
输出中位数,保留小数点后一位。
Sample Input
4
3
6
4
5
Sample Output
4.5
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 100;
int num[N];
int main(){
int n;
scanf("%d", &n);
for(int i = 0; i < n; i++){
scanf("%d", &num[i]);
}
sort(num, num + n);
if(n % 2 == 0){
if((num[n / 2] + num[n / 2 - 1]) % 2 == 0){
printf("%.1f\n", (num[n / 2] + num[n / 2 - 1]) / 2.0);
}
else{
printf("%.1f\n",(1.0*num[n/2]/1.0+num[n/2-1]/1.0)/ 2.0);
}
}
else{
printf("%.1f\n", num[n / 2]/1.0);
}
return 0;
}