为什么.Average()方法不起作用?和错误CS1061解释



我正试图解决codewars.com中名为";你到底有多优秀">

挑战描述:你班上有一次考试,你通过了。祝贺你!但你是个雄心勃勃的人。你想知道你是否比班上的普通学生好。你会收到一个包含同龄人考试成绩的数组。现在计算平均值并比较你的分数!如果你更好,返回True,否则返回False!注:你的分数不包括在你班级的分数数组中。为了计算平均点,您可以将您的点添加到给定的数组中!

我的解决方案:

public class Kata
{
public static bool BetterThanAverage(int[] ClassPoints, int YourPoints)
{
ClassPoints = ClassPoints.Append(YourPoints).ToArray(); // Add Yourpoints to the ClassPoints array
int AveragePoints = ClassPoints.Average(); // Get average points
if (YourPoints > AveragePoints) { // Compare
return true;
} else {
return false;
}
}
}

我得到的错误:

src/Solution.cs(5,31(:错误CS1061:'int[]'不包含'Append'的定义,并且找不到接受'int[]‘类型的第一个参数的可访问扩展方法'Append'(是否缺少using指令或程序集引用?(找不到接受"int[]"类型的第一个参数的"Average"(是否缺少using指令或程序集引用?(

我试图查看错误代码,但无法理解解释。我的代码出了什么问题,这个挑战很简单,但我不明白为什么简单的方法不起作用?

更新。找到的解决方案:感谢大家提供的解决方案。@MikeT提出的代码正在运行并通过了测试,但感觉我偏离了要求。

正在解决的任务在codewars.org编辑器中,而不是在Visual Studio中。任务本身是预定义的,我决定不改变它。但下面是我的新代码:

public class Kata
{
public static bool BetterThanAverage(int[] ClassPoints, int YourPoints)
{    
int SumClassPoints = 0;
int Average = 0;
for (int i=0; i < ClassPoints.Length; i++) {
SumClassPoints += ClassPoints[i];    
}
Average = (SumClassPoints + YourPoints) / (ClassPoints.Length + 1);
if (YourPoints > Average) {
return true;
} else {
return false;
}
}
}
```

2问题首先,您使用了错误的类型,让编译器来计算转换,并且您使用了需要添加到代码库的扩展函数

首先是在数组中传递的类型,然后用Append将其转换为Ienumerable,然后转换为数组,然后调用average,它也是Ienumeraable函数,average也返回一个double而不是int,由于将double转换为int可能会丢失数据,因此它不会隐式转换,并且需要在AveragePoints或平均函数的输出上进行显式转换

第二个c#允许您从包含方法public static MyExpander(this <class to apply to> myClass)的静态类扩展类函数。但是,如果您没有告诉编译器您正在使用它们,它就不知道它们存在,在这种情况下,扩展函数位于System.Linq命名空间中,因此您必须使用

using System.Linq;
using System.Collections.Generic;
public class Kata
{
public static bool BetterThanAverage(IEnumerable<int> ClassPoints, int YourPoints)
{
ClassPoints = ClassPoints.Append(YourPoints); // Add Yourpoints to the ClassPoints array
int AveragePoints =(int) ClassPoints.Average(); // Get average points
if (YourPoints > AveragePoints)
{ // Compare
return true;
}
else
{
return false;
}
}
}

相关内容

最新更新