I have this an assignment where the user has to enter in a name, then a score, and repeat that process until they are done, press Q, and then the array will show the names and scores, then give an average of all of those scores. What I have right now is this.
static void inputPartInformation(string[] pl, double[] sc)
{
int i = 0;
do
{
Console.Write("Enter The Player's Name: ");
pl[i] = Console.ReadLine();
Console.Write("Enter Their Score: ");
sc[i] = double.Parse(Console.ReadLine());
}
while (pl[i++].CompareTo("Q") != 0);
}
static void displayParts(string[] pl, double[] sc)
{
int i = 0;
while (pl[i].CompareTo("Q") != 0)
{
Console.WriteLine("{0,15}{1,6}", pl[i], sc[i]);
++i;
}
}
static void Main(string[] args)
{
String[] players = new String[100];
double[] scores = new double[100];
inputPartInformation(players, scores);
displayParts(players, scores);
double average = scores.Average();
Console.WriteLine("The Average is: {0}", average);
Console.ReadLine();
}
When I try to average the scores, it doesn’t come out properly.
The problem is with the call of
Average: you are averaging everything, not everything up to the"Q"in the correspondingnamesposition. You are adding together all these zeros in the scores part to which you did not write, and then divide it by 100 – the length of the entire array.The easiest way to address this issue is to return the position of the
"Q"entry from theinputPartInformationmethod:Now you can use LINQ’s
Takefunction to get the correct average: