📜  c#奇偶中位数 - C#代码示例

📅  最后修改于: 2022-03-11 14:49:19.034000             🧑  作者: Mango

代码示例1
public static void Main(string[] args)
        {
            int[] a = { 1, 4, 5, 8, 19, 12, 15 };

            List l = new List(a); l.Sort();
            List even = new List();   //hold even numbers
            List odd = new List();    //hold odd numbers
            int medianOdd;
            int medianEven;

            foreach (int num in l)
            {
                if (num % 2 == 0) even.Add(num);
                else odd.Add(num);
            }                                   //formula for median with odd vs even total length
            if (even.Count % 2 != 0) medianEven = even[even.Count / 2];
            else medianEven = (even[(even.Count - 1) / 2] + even[even.Count / 2]) / 2;

            if (odd.Count % 2 != 0) medianOdd = odd[odd.Count / 2];
            else medianOdd = (odd[(odd.Count - 1) / 2] + odd[odd.Count / 2]) / 2;

            Console.Write($"Even Median = {medianEven}  Odd Median = {medianOdd}");
            //median w/ Odd total length = length/2       vs Even length = (   (length/2 -1) + (length/2)  )  /2
        }