A median is described as the numeric value separating the higher half of a list, from the lower half. The median of a finite list of numbers can be found by arranging all the elements from lowest value to highest value and picking the middle one. If there is an even number of elements, the median is then defined to be the mean of the two middle values. Now, could you write a PRogram to help to find the median?
There are multiple test cases. The first line of input is an integer T ≈ 100 indicating the number of test cases.
The first line of each test is an integer 0 < n < 500 indicating the number of elements. The second line consists of n numbers, the elements of the list, whose absolute values are smaller than 1,000,000.
For each test case, output the median, with 3 decimal digits.
310.041.0 1000.3 100.2 10.152.0 3.0 5.0 7.0 11.0Sample Output
0.00055.1505.000References
http://en.wikipedia.org/wiki/Median
Author: WU, ZejunContest: The 8th Zhejiang Provincial Collegiate Programming Contest题意:求数列中位数。若有偶数个,找最中间两数的平均数。
#include <iostream>#include <cstdio>#include <string>#include <cstring>#include <algorithm>#include <cmath>#include <queue>#include <vector>#include <set>#include <stack>#include <map>#include <climits>using namespace std;#define LL long longconst int INF=0x3f3f3f3f;int main(){ int t,n; double a[1000]; scanf("%d",&t); while(t--) { scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%lf",&a[i]); sort(a+1,a+n+1); if(n%2==1) printf("%.3lf/n",a[n/2+1]); else printf("%.3lf/n",(a[n/2]+a[n/2+1])/2); } return 0;}
新闻热点
疑难解答