您的位置:首页 > 产品设计 > UI/UE

Problem A: Median Value

2015-07-23 09:18 489 查看

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: