// Program calls a method that finds and returns // the median value in an array
ID: 3551797 • Letter: #
Question
// Program calls a method that finds and returns
// the median value in an array
// The median value is the middle value from largest to smallest
// If there are an even number of values, the
//median is the mean of the two middle values
using System;
class DebugSeven4
{
private static void Main()
{
int[] firstArray = {10, 9, 2, 3, 5, 6};
int[] secondArray = {112, 456, 782}; // changed () to {}
int[] thirdArray = {9, 12, 45, 82, 84, 67, 2, 6};
Console.WriteLine("The median value of the first array is {0}",
FindMedian(firstArray));
Console.WriteLine("The median value of the second array is {0}",
FindMedian(secondArray));
Console.WriteLine("The median value of the third array is {0}",
FindMedian(thirdArray));
}
private static double FindMedian(int[] array)
{
double median;
median = array.Length / 2; //changed middle to median
Array.Sort(array);
if (array.Length % 2 == 0)
median = (double)(array[array.Length - 1] + array[array.Length]) / 2; // changed middle to array.length
else
median = array[array.Length]; // changed middle to array.length
return median;
}
}
Explanation / Answer
/* corrected code*/
/* link at : http://ideone.com/xacnNT */
using System;
class DebugSeven4
{
private static void Main()
{
int[] firstArray = {10, 9, 2, 3, 5, 6};
int[] secondArray = {112, 456, 782}; // changed () to {}
int[] thirdArray = {9, 12, 45, 82, 84, 67, 2, 6};
Console.WriteLine("The median value of the first array is {0}",
FindMedian(firstArray));
Console.WriteLine("The median value of the second array is {0}",
FindMedian(secondArray));
Console.WriteLine("The median value of the third array is {0}",
FindMedian(thirdArray));
}
private static double FindMedian(int[] array)
{
double median;
median = array.Length / 2; //changed middle to median
Array.Sort(array);
if (array.Length % 2 == 0)
median = (double)(array[array.Length/2 - 1] + array[array.Length/2]) / 2; // changed middle to array.length/2
else
median = array[array.Length/2]; // changed middle to array.length
return median;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.