C# 获取数组的平均值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11979321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting the Average of an Array
提问by user1580598
I have this an assignment where the user has to enter in a name, then a score, and repeat that process until they are done, press Q, and then the array will show the names and scores, then give an average of all of those scores. What I have right now is this.
我有一个作业,用户必须输入名称,然后输入分数,然后重复该过程,直到完成,按 Q,然后数组将显示名称和分数,然后给出所有这些的平均值分数。我现在拥有的是这个。
static void inputPartInformation(string[] pl, double[] sc)
{
int i = 0;
do
{
Console.Write("Enter The Player's Name: ");
pl[i] = Console.ReadLine();
Console.Write("Enter Their Score: ");
sc[i] = double.Parse(Console.ReadLine());
}
while (pl[i++].CompareTo("Q") != 0);
}
static void displayParts(string[] pl, double[] sc)
{
int i = 0;
while (pl[i].CompareTo("Q") != 0)
{
Console.WriteLine("{0,15}{1,6}", pl[i], sc[i]);
++i;
}
}
static void Main(string[] args)
{
String[] players = new String[100];
double[] scores = new double[100];
inputPartInformation(players, scores);
displayParts(players, scores);
double average = scores.Average();
Console.WriteLine("The Average is: {0}", average);
Console.ReadLine();
}
When I try to average the scores, it doesn't come out properly.
当我尝试平均分数时,结果不正确。
采纳答案by dasblinkenlight
The problem is with the call of Average: you are averaging everything, not everything up to the "Q"in the corresponding namesposition. You are adding together all these zeros in the scores part to which you did not write, and then divide it by 100 - the length of the entire array.
问题在于 的调用Average:您正在对所有内容进行平均,而不是"Q"对相应names位置的所有内容进行平均。您将未写入的分数部分中的所有这些零相加,然后将其除以 100 - 整个数组的长度。
The easiest way to address this issue is to return the position of the "Q"entry from the inputPartInformationmethod:
解决此问题的最简单方法是"Q"从inputPartInformation方法返回条目的位置:
var count = inputPartInformation(players, scores);
Now you can use LINQ's Takefunction to get the correct average:
现在您可以使用 LINQ 的Take函数来获得正确的平均值:
double average = scores.Take(count).Average();
回答by ja72
I suggest you count how many scores have been entered (in a variable N) and use the .Take(N)function to only return an array of Nscores.
我建议您计算输入了多少分数(在变量中N)并使用该.Take(N)函数仅返回N分数数组。
Example:
例子:
double[] list = new double[100];
// assumed first N values are filled only.
// N = ...
list = list.Take(N).ToArray();
double average = list.Average();
回答by Fun Pants
Do you have to use an array? Using a List may be a better choice as you simply add onto it as long as they keep adding scores. That way when they quit and you go to take the average, it won't contain any 0's that are not entered scores.
你必须使用数组吗?使用列表可能是更好的选择,因为只要它们不断添加分数,您只需添加到列表中即可。这样当他们退出并且你去取平均值时,它不会包含任何未输入分数的 0。

