[MM60-易] Find The Median
Problem Description
In statistics, the value (also called median) represents a sample, population or probability distribution of a numeric value. The value of the collection can be divided into equal two parts. For a limited number set, you may sort all the observations and find the level of the middle one as the value. If there is an even number of observations that means the median is not unique, we often taking the average of the two middle values as the median. Please write a program find the median for the given unsorted sequence.
Input File Format
A line containing several integers.
Output Format
Output the median in one line with format as shown in the examples.
Example
In statistics, the value (also called median) represents a sample, population or probability distribution of a numeric value. The value of the collection can be divided into equal two parts. For a limited number set, you may sort all the observations and find the level of the middle one as the value. If there is an even number of observations that means the median is not unique, we often taking the average of the two middle values as the median. Please write a program find the median for the given unsorted sequence.
Input File Format
A line containing several integers.
Output Format
Output the median in one line with format as shown in the examples.
Example
Sample Input: | Sample Output: |
2 100 31 1 4 40 55 10 2001 100 | Median=35.5 |
5 21 9 17 4 10 2010 11 19 | Median=11 |
100 1 2 90 56 33 12 99 119 2012 78 | Median=78 |
- #include <iostream>
- #include <algorithm>
- #include <string>
- #include <sstream>
- #include <stdio.h>
- #include <ctype.h>
- #include <cmath>
- using namespace std;
- int main() {
- // [MM60-易] Find The Median
- string text;
- int num[10000];
- while(getline(cin, text))
- {
- int count = 0;
- stringstream ss(text);
- string token;
- while (getline(ss, token, ' '))
- {
- num[count] = stoi(token);
- count++;
- }
- sort(num, num+count);
- if(count % 2 == 0)//偶數
- {
- cout << "Median=" << double((double(num[(count/2)-1])+double(num[count/2]))/2) << endl;
- }
- else
- {
- cout << "Median=" << num[(int)floor(count/2)] << endl;
- }
- }
- return 0;
- }
沒有留言:
張貼留言