简体   繁体   中英

Need to calculate an average in C# from an Array

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).

    const int sizeOfNums;   
    int[] hours = new int[sizeOfNums];
    const float amountToMultiply =123.44f;

    //Load up you numbers from text file into hours

    float multipliedAverage = 0.0f;

    for(int i=0; i< sizeOfNums; i++)
    {
        multipliedAverage += hours[i];
    }
    multipliedAverage = (multipliedAverage/ sizeOfNums) * amountToMultiply;

Other way: Convert hour array to list and use LINQ:

var hrsList = hours.ToList();
var avr = hrsList.Select(x => x * constantValue).Average();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM