2018年1月12日 星期五

[MM60-易] Find The Median(C++)

[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

Sample Input:Sample Output:
2 100 31 1 4 40 55 10 2001 100Median=35.5
5 21 9 17 4 10 2010 11 19Median=11
100 1 2 90 56 33 12 99 119 2012 78Median=78

  1. #include <iostream>  
  2. #include <algorithm>  
  3. #include <string>  
  4. #include <sstream>  
  5. #include <stdio.h>  
  6. #include <ctype.h>  
  7. #include <cmath>  
  8. using namespace std;  
  9.   
  10. int main() {  
  11.     // [MM60-易] Find The Median  
  12.     string text;  
  13.     int num[10000];  
  14.       
  15.     while(getline(cin, text))  
  16.     {  
  17.         int count = 0;  
  18.         stringstream ss(text);  
  19.         string token;  
  20.         while (getline(ss, token, ' '))  
  21.         {  
  22.             num[count] = stoi(token);  
  23.             count++;  
  24.         }  
  25.         sort(num, num+count);  
  26.         if(count % 2 == 0)//偶數  
  27.         {  
  28.             cout << "Median=" << double((double(num[(count/2)-1])+double(num[count/2]))/2) << endl;  
  29.         }  
  30.         else  
  31.         {  
  32.             cout << "Median=" << num[(int)floor(count/2)] << endl;  
  33.         }  
  34.     }  
  35.     return 0;  
  36. }  

沒有留言:

張貼留言