Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...