Problem A: Median Value

Problem A: Median Value

求中位數:

  • 一組數,如果是奇數的話,就是中間的一個數;偶數的話就是中間兩數的平均值。
  • 思路:輸入指定個數的浮點數 循環保存到數組裏,再將數組排序,根據數組角標找中間的數組進行處理
  • 用到頭文件 iomanip.h 按照指定精度輸出數據
cout<<fixed<<setprecision(x)<<

http://acm.cug.edu.cn/JudgeOnline/problem.php?cid=1046&pid=0

Description

Figure out the median of a floating point number array. If the size of
an array is an odd number, the median is the middle element after
arranging all the array elements from lowest value to highest value;
If there is an even number of elements, then there is no single middle
value, so the median is the mean of the two middle values.

**找出中位數的一個浮點數的數組。如果一個數組的大小是一個奇數,中位數是中間元素後安排所有的數組元素從最小值到最大值;如果有偶數的元素,那麼沒有單一的中間值,中值是
兩個中間值的平均值。**

Input

The input may contain several test cases.

The first line of each test case is an integer n (n >= 1),
representing the size of the array.

The second line of each test case contains all the elements in the
array.

Input is terminated by EOF.

*輸入可能包含幾個測試用例。      
每個測試用例的第一行是一個整數n(n > = 1),代表了數組的大小。
第二行每個測試用例包含的所有元素的數組。      
輸入是通過EOF終止。*

Output

For each test case, output the median , which must be formatted as a
floating point number with exactly two digit after the decimal point.

Sample Input

6
5.0 4.0 3.0 2.0 11.0 3.0 11
5.0 6.0 222.0 23.0 23.0 4.0 2.0 5.0 99.0 1.0 8.0 Sample Output

3.50
6.00

AC代碼

#include <iostream>
#include <iomanip>
#define maxn 100
using namespace std;
void sort(float* list, int len){
  int i,j;
  float temp;
  for(i=0;i<len-1;++i){
    for(j=0;j<len-i-1;j++){
      if(list[j+1]<list[j]){
        temp=list[j+1];
        list[j+1]=list[j];
        list[j]=temp;
      }
    }
  }
}
int main(){
  int n;
  float a[maxn];
  cin>>n;
  for(int i=0;i<n;i++)
    cin>>a[i];
  sort(a,n);
  if(n % 2 == 0)
    cout<<fixed<<setprecision(2)<<((a[n/2]+a[n/2-1])/2)<<endl;
  else
    cout<<fixed<<setprecision(2)<<a[n/2]<<endl;
  return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章