Just wanted to ask any C# experts out there for some help. I've been struggling with this for a while and just can't figure it out. Basically, I have an array from a text file with 50 numbers (integers). I need to take those 50 numbers, multiply them by a constant and get the average. Trouble is I cannot for the life of me work out how to get the average of the calculated numbers and not just the numbers from the array. Any help is greatly appreciated!
Here is my code so far:
int[] hours = new int[50];
// populate values code goes here
int total = 0;
double average = 0;
for (int index = 0; index < hours.Length; index++)
{
total = total + hours[index];
}
//average = total / numbers.Length; // Integer division int / int = int
average = (double)total / hours.Length;
Console.WriteLine("Total = " + total);
Console.WriteLine("Average = " + average.ToString("N2"));
Full code here.
You can use LINQ to average the value:
var avg = hours.DefaultIfEmpty(0).Average(x => x) * constantValue;
.DefaultIfEmpty(0)
stops .Average()
from throwing an exception on an empty list (it will now return 0 in that case).