【问题标题】:Need to calculate the median and mode, C#需要计算中位数和众数,C#
【发布时间】:2022-01-06 21:30:12
【问题描述】:

我需要组织数字并从任意数量的数字中获取中位数和众数,因此我尝试了不同的方法来实现这一点,但我无法得到解决方案。

public static void Main()
        {
            int i, n;
            int[] a = new int[100];
    
            Console.Write("\n\nRead n number of values in an array and display it in reverse order:\n");
            Console.Write("------------------------------------------------------------------------\n");
    
            Console.Write("Input the number of elements to store in the array :");
            n = Convert.ToInt32(Console.ReadLine());
    
    //quantity of numbers to insert
            Console.Write("Input {0} number of elements in the array :\n", n);
            for (i = 0; i < n; i++)
            {
                Console.Write("element - {0} : ", i);
                a[i] = Convert.ToInt32(Console.ReadLine());
            }
    //individial numbers to insert
            Console.Write("\nThe values store into the array are : \n");
            for (i = 0; i < n; i++)
            {
                Console.Write("{0}  ", a[i]);
            }
}

我试过用这个,但是不知道怎么用

public static class Extensions
{
    public static decimal GetMedian(this int[] array)
    {
        int[] tempArray = array;
        int count = tempArray.Length;

        Array.Sort(tempArray);

        decimal medianValue = 0;

        if (count % 2 == 0)
        {
            // count is even, need to get the middle two elements, add them together, then divide by 2
            int middleElement1 = tempArray[(count / 2) - 1];
            int middleElement2 = tempArray[(count / 2)];
            medianValue = (middleElement1 + middleElement2) / 2;
        }
        else
        {
            // count is odd, simply get the middle element.
            medianValue = tempArray[(count / 2)];
        }

        return medianValue;
    }
}

【问题讨论】:

标签: c# median mode


【解决方案1】:

Median 是已排序集合中的一个中间项(或两个中间项的平均值):

 using System.Linq;

 ...

 int[] a = ...

 ...

 double median = a
   .OrderBy(item => item)     // from sorted sequence
   .Skip((a.Length - 1) / 2)  // we skip leading half items
   .Take(2 - a.Length % 2)    // take one or two middle items 
   .Average();                // get average of them  

众数是分布的局部最大值,其中出现频率最高的元素:

 int mode = a
   .GroupBy(item => item)                      
   .OrderByDescending(group => group.Count())
   .First(group => group.Key);   

【讨论】:

    猜你喜欢
    • 2019-03-07
    • 2021-05-12
    • 2013-11-24
    • 1970-01-01
    • 1970-01-01
    • 2020-01-06
    • 2016-10-04
    • 2021-01-17
    • 1970-01-01
    相关资源
    最近更新 更多