Calculate median in c#

前端 未结 12 1479
别跟我提以往
别跟我提以往 2020-11-29 23:35

I need to write function that will accept array of decimals and it will find the median.

Is there a function in the .net Math library?

12条回答
  •  死守一世寂寞
    2020-11-30 00:21

    Below code works: but not very efficient way. :(

    static void Main(String[] args) {
            int n = Convert.ToInt32(Console.ReadLine());            
            int[] medList = new int[n];
    
            for (int x = 0; x < n; x++)
                medList[x] = int.Parse(Console.ReadLine());
    
            //sort the input array:
            //Array.Sort(medList);            
            for (int x = 0; x < n; x++)
            {
                double[] newArr = new double[x + 1];
                for (int y = 0; y <= x; y++)
                    newArr[y] = medList[y];
    
                Array.Sort(newArr);
                int curInd = x + 1;
                if (curInd % 2 == 0) //even
                {
                    int mid = (x / 2) <= 0 ? 0 : (newArr.Length / 2);
                    if (mid > 1) mid--;
                    double median = (newArr[mid] + newArr[mid+1]) / 2;
                    Console.WriteLine("{0:F1}", median);
                }
                else //odd
                {
                    int mid = (x / 2) <= 0 ? 0 : (newArr.Length / 2);
                    double median = newArr[mid];
                    Console.WriteLine("{0:F1}", median);
                }
            }
    
    }
    

提交回复
热议问题