zoukankan      html  css  js  c++  java
  • Median Value

    Problem A: Median Value
    Time Limit: 1 Sec Memory Limit: 128 MB
    Submit: 874 Solved: 307
    [Submit][Status][Web Board]
    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.

    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

    问题描述:
    该题为水题,只需注意数组中长度。数组长度为奇数时,输出中间值即可;若数组长度为偶数,输出中间两数和的一半。
    另外注意输出保留小数点位两位,采用cout<

    #include <iostream> 
    #include <iomanip> 
    using namespace std; 
    void sort(float* shu, int length) { 
        int i, j; 
        float temp; 
        for (i = 0; i<length - 1; ++i) { 
            for (j = 0; j<length - i - 1; j++) { 
                if (shu[j + 1]<shu[j]) { 
                    temp = shu[j + 1]; 
                    shu[j + 1] = shu[j]; 
                    shu[j] = temp; 
                } 
            } 
        } 
    } 
    int main() { 
        int n; 
        float a[101]; 
        while (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; 
    } 
    /************************************************************** 
        Problem: 1009 
        User: 20151000332 
        Language: C++ 
        Result: Accepted 
        Time:12 ms 
        Memory:1268 kb 
    
  • 相关阅读:
    DFS迷宫递归所有路径 新手入门
    【翻译】Ext JS最新技巧——2016-3-4
    Android进程通信之一:两种序列化方式
    Ext JS 6应用程序Build后出现“c is not a constructor return new c(a[0])”的处理
    简约才是王道? CardView 的使用
    经过一段的努力,终于成为CSDN博客专家,感谢大家支持
    ACM_Uppercase(水题)
    ACM_01背包
    2018年北京信息科技大学第十届程序设计竞赛暨ACM选拔赛-B-precise math function
    goj N皇后问题
  • 原文地址:https://www.cnblogs.com/bryce1010/p/9387478.html
Copyright © 2011-2022 走看看