Answer the question
In order to leave comments, you need to log in
Does the task give the wrong value (working with delegates and anonymous methods)?
The essence of the task is simple - you need to create a project according to the Console Application (.NET Core) template. Create an anonymous method that takes an array of delegates as an argument and returns the arithmetic mean of the return values of the methods reported with the delegates in the array. Methods declared with array delegates return a random value of type int.
My decision:
using System;
namespace ConsoleApp44
{
public delegate int Number();
public delegate int MediumCalc(Number[] arrayX);
class Program
{
public static int Randomizer()
{
Random rand = new Random();
return rand.Next(1, 10);
}
static void Main(string[] args)
{
Number[] numArr = new Number[5];
for(int i = 0; i < numArr.Length; i++)
{
numArr[i] = Randomizer;
Console.Write(" " + numArr[i].Invoke() + " ");
}
Console.WriteLine();
MediumCalc mediumCalc = delegate (Number[] arrayX)
{
int sum = 0;
for (int i = 0; i < arrayX.Length; i++)
{
sum += arrayX[i]();
}
return ((sum) / (arrayX.Length));
};
Console.WriteLine(mediumCalc(numArr));
Console.ReadKey();
}
}
}
Answer the question
In order to leave comments, you need to log in
First, when outputting to the console, a new number is generated. As a result, one set of numbers is displayed on the screen, and another in the program. Why invoke, I can't understand.
Second, it's wrong to write public static int Randomizer() => new Random().Next(1, 10). It is necessary to create a static field, which is initialized with a generator. Dalle in the method simply return the following value: public static int Randomizer() => rand.Next(1, 10)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question