Reputation: 61
Here is the question i need to solve:
This is what i have done so far,everything except the calculate total score and subract highest and lowest from total score and im not sure where im suppose to put the code and what code I'm suppose to use:
double[] scores = { 8.7, 9.3, 7.9, 6.4, 9.6, 8.0, 8.8, 9.1, 7.7, 9.9, 5.8, 6.9 };
Console.WriteLine("Numbers in the list:" + scores.Length);
for (int index = 0; index < scores.Length; index++)
{
Console.WriteLine(scores[index]);
}
//highest number
double high = scores[0];
for (int index = 1; index < scores.Length; index++)
{
if (scores[index] > high)
{
high = scores[index];
}
}
Console.WriteLine("Highest number =" + high);
//lowest number
double low = scores[0];
for (int index = 1; index < scores.Length; index++)
{
if (scores[index] < low)
{
low = scores[index];
}
}
Console.WriteLine("lowest number =" + low);
//average of the scores
double total = 0;
double average = 0;
for (int index = 0; index < scores.Length; index++)
{
total = total + scores[index];
}
average = (double)total / scores.Length;
Console.WriteLine("Total=" + total);
Console.WriteLine("Average=" + average.ToString("N2"));
Console.ReadKey();
}
Upvotes: 1
Views: 3240
Reputation: 5380
For the sake of completeness, I'd like to propose a solution that will handle the case where there might be more than one element in the array with the max value or min value:
double[] scores = { 8.7, 9.3, 7.9, 6.4, 9.6, 8.0, 8.8, 9.1, 7.7, 9.9, 5.8, 6.9, 9.9, 5.8 };
var resultValue = scores.Where(e => e != scores.Max() && e != scores.Min()).Sum();
Cheers
NOTE: Yes, it might become inefficient if the list is long, as e.Max() and e.Min() will be called many times, and they will iterate the whole list many times. But according to the problem statement, there's only 12 values. I wanted to leave it as a 1 liner, but if more values were to be handled, then caching the Max and Min values would be better.
Upvotes: 0
Reputation: 8231
double[] scores = { 8.7, 9.3, 7.9, 6.4, 9.6, 8.0, 8.8, 9.1, 7.7, 9.9, 5.8, 6.9 };
double min = scores.Min();
double max = scores.Max();
double total = scores.Sum();
double result = total - min - max;
Upvotes: 1
Reputation: 4230
If you are using .NET 3.5+ , you can use LINQ Sum()
, Min()
and Max()
functions. To do this you need to add using System.Linq;
double[] scores = { 8.7, 9.3, 7.9, 6.4, 9.6, 8.0, 8.8, 9.1, 7.7, 9.9, 5.8, 6.9 };
double calculatedValue = scores.Sum() - scores.Max() - scores.Min();
Upvotes: 7