【发布时间】: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;
}
}
【问题讨论】:
-
如果你想使用
tempArray,你应该复制array到tempArray。int[] tempArray = array;只是对array的另一个引用,当对tempArray进行排序时,您也会对array进行排序