查找数组的算术平均值:C# [英] Finding the Arithmetic Mean of an Array: C#
问题描述
语言: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("\n How many numbers do you want to average? \n");
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;
}
现在,我该怎么做才能将数组中的所有数字加在一起,然后将其除以array.Length?在此先感谢:D
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
推荐答案
如果需要将int作为结果,怎么做:
If you need an int as the result, how about:
int average = Convert.ToInt32(nListToAverage.Average());
否则,您会得到更精确的答案:
Otherwise, you get a more precise answer with a double:
double average = nListToAverage.Average();
如果需要先添加所有项目,则还可以执行以下操作:
If you need to add all the items first, you can also do:
int average = nListToAverage.Sum() / nListToAverage.Length;
或者用老式的工作方式:
Or the old-school, show-your-work way:
int sum = 0;
int average = 0;
int numItems = nListToAverage.Length;
if (numItems > 0)
{
for(int i = 0; i < numItems; i++)
{
sum += nListToAverage[i];
}
average = sum / numItems;
}
这篇关于查找数组的算术平均值:C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!