I'm new to coding at all languages and as part of my course we are finding the median. Someone kindly helped me using constructors which my tutor has told me is quite a complex way to do it Is there an easier way than the code I attach.
The code also produces the wrong median so there is something wrong with the logic. I was told it should be:
(numberList.Count/2) and (numberList.Count/2 - 1), not -1 and -2?
Anyway the code below is what I have, please help me find the correct median in the most efficient way. Please also remember you're also speaking to someone with minimal understanding.
public class FindMedian
{
public List<int> numbersList = new List<int>(); // list to store user input
// constructor
public FindMedian(int n)
{
Console.WriteLine("Please Enter " + n + " numbers. \n\n");
for (int i = 1; i < n + 1; i++)
{
Console.WriteLine("Number " + i + " : ");
numbersList.Add(GetUserInput()); // call's GetUserInput
}
PrintData();
}
// returns int from Console. Will continue to run until a valid int is entered
private int GetUserInput()
{
int temp = 0;
bool numberValid = false;
while (!numberValid)
{
try
{
temp = int.Parse(Console.ReadLine());
numberValid = true;
}
catch
{
Console.WriteLine("Invalid entry. Please try again.\n");
numberValid = false;
}
}
return temp;
}
// prints data after user enteres the correct number of ints
private void PrintData()
{
// If list contains no data
if (numbersList.Count < 3)
{
Console.WriteLine("No User Data Entered");
return;
}
numbersList.Sort(); // Sorts list from smallest to largest
int minimum = numbersList[0];
int median;
// if list count is even and median is average of two middle numbers
if (numbersList.Count % 2 == 0)
{
median = (numbersList[(numbersList.Count / 2) - 2] + numbersList[(numbersList.Count / 2) - 1] / 2);
}
// if list count is odd and median is just middle number
else
{
median = numbersList[(numbersList.Count / 2)];
}
Console.WriteLine("Minimum Number : " + minimum);
Console.WriteLine("Median Number : " + median);
}
}