Jav*_*ael 2 c# math mode median
我需要组织数字并从任意数量的数字中获取中位数和众数,所以我尝试了不同的方法来实现这一点,但我就是无法找到解决方案。
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]);
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用这个,但我不知道如何使用它
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;
}
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
众数是分布的局部最大值,即其中出现频率最高的元素:
int mode = a
.GroupBy(item => item)
.OrderByDescending(group => group.Count())
.First().Key;
Run Code Online (Sandbox Code Playgroud)