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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值