Hi I am trying to create the following method in C# Create a method last3YearInInches. It should take in an ArrayList (Java) or List (C#) of Doubles.
■ If the size of the list is less than 3, return 100
■ Otherwise take the LAST 3 items in the list and average them together.
■ Return the average
This is what I have to far but I am getting errors when trying to use only the last three of the list.
public double last3YearsInInches(List<Double> list )
{
if(list.Count < 3)
{
return 100;
}
else
{
double lastThree= list.Reverse<Double>().Take(3);
double average = lastThree / 3;
return average;
}
}
CodePudding user response:
Try using a for loop instead.
However, the reason the your code didn't work, is because you are trying to set a type of double
to a IEnumerable<Double>
. In C#, you would have to cast this (if you could) or just create the variable average
as the same type the Take()
and Reverse<>
method return. For example, if you had a method that returned a bool
, you can't set int i
equal to that method because you would be setting two different types to eachother. You can also do what Dmitry had commented as this would just return the type of double, double lastThree= list.Reverse<Double>().Take(3).Average();
public static double last3YearsInInches(List<Double> list)
{
Double average = 0.0;
if (list.Count < 3)
{
return 100;
}
else
{
//using a for loop instead of .take() to get the last three elements
for(int i = list.Count - 3; i < list.Count; i )
{
average = list[i];
}
return average / 3;
}
}
CodePudding user response:
list.Reverse<Double>().Take(3);
returns an object: List that has 3 items inside.
Correct, "else" statement:
else
{
List<Double> lastThree= list.Reverse<Double>().Take(3);
double average = (lastThree[0] lastThree[1] lastThree[2]) / 3;
return average;
}