Reputation: 53
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.
Upvotes: 3
Views: 21781
Reputation: 21
Do you have to use an array? Using a List may be a better choice as you simply add onto it as long as they keep adding scores. That way when they quit and you go to take the average, it won't contain any 0's that are not entered scores.
Upvotes: 1
Reputation: 29274
I suggest you count how many scores have been entered (in a variable N
) and use the .Take(N)
function to only return an array of N
scores.
Example:
double[] list = new double[100];
// assumed first N values are filled only.
// N = ...
list = list.Take(N).ToArray();
double average = list.Average();
Upvotes: 1
Reputation: 727047
The problem is with the call of Average
: you are averaging everything, not everything up to the "Q"
in the corresponding names
position. 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 the inputPartInformation
method:
var count = inputPartInformation(players, scores);
Now you can use LINQ's Take
function to get the correct average:
double average = scores.Take(count).Average();
Upvotes: 5