(2017-1)中位数

问题描述

给定一个整数序列,求中位数。如果序列个数为奇数,中位数为升序的中间位置,如果是偶数,这位升序的中间两个数的平均值。

输入

输入包含多组测试数据,每一组第一行为n(n<10^4)表示这个序列的个数,接下来有n个整数k(0<k<2^31-1)

输出

输出这个序列的中位数

样例输入1:

5
2 1 4 3 5

样例输出1:

3

样例输入2:

4
1 4 3 2

 样例输出2:

3

思路:

对于奇数、偶数个数字,要分开讨论。

%.lf 表示四舍五入到个位

%.2lf 表示四舍五入到小数点后两位

#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 10010;
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){     //n为偶数
        if((num[n / 2] + num[n / 2 - 1]) % 2 == 0){     //中间两位平均值为整数
            printf("%d\n", (num[n / 2] + num[n / 2 - 1]) / 2);
        }
        else{
            printf("%.lf\n", (num[n / 2] + num[n / 2 - 1]) / 2.0);
        }
    }
    else{       //n为奇数
        printf("%d\n", num[n / 2]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_35093872/article/details/87966520