V
V
Vitaly Kolesnik2018-02-14 22:58:55
OOP
Vitaly Kolesnik, 2018-02-14 22:58:55

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();
        }
    }
}

But there is a problem - as a result, it gives out the wrong environment. arithmetic value.
Let's say if the Randomizer() method "spit out" 5 numbers - {6, 8, 6, 3, 5}
And mediumCalc(numArr) returns { 3 }.
Which is completely illogical from my point of view ( (6 + 8 + 6 +3 + 5) / (5) != 3)
Tell me, maybe I messed something up or messed up somewhere!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Griboks, 2018-02-14
@VK28111995

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 question

Ask a Question

731 491 924 answers to any question