Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

Finding the Arithmetic Mean of an Array: C#

Language: C#

I have an array of numbers that the user entered, and I want to find the arithmetic mean of the array.

I looked up a couple of similiar cases, but couldn't really find anything I was looking for... Anyway, here is the code:

            Console.WriteLine("
 How many numbers do you want to average? 
");

            int nNumtoAvg = Convert.ToInt32(Console.ReadLine());


            int[] nListToAverage = new int[nNumtoAvg];



            for (int i = 0; i < nNumtoAvg; i++)
            {

                Console.WriteLine("Enter whole number #" + (i + 1) + ": ");

                string sVal = Console.ReadLine();

                int nValue = Convert.ToInt32(sVal);

                nListToAverage[i] = nValue;

            }

Now, what would I do to add all the numbers in the array together, and then divide that by the array.Length? Thanks in advance :D

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could do this many ways but I would do the following after your for loop.

int sum = 0;
for (int i = 0; i < nNumtoAvg; i++)
     sum += nListToAverage[i];

int result = sum / nNumtoAvg;   // result now has the average of those numbers.

You could also do it in the for loop you already have but it wont really make a difference in complexity if you don't have very much numbers to input.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...