mardi 1 octobre 2019

Calling a method that returns a random number from inside a loop [duplicate]

This question already has an answer here:

I have a 'for' loop that calls a method that returns a random number between 1 and 10. The loop then writes this number to the console. When I run the code normally it always returns the same number. However, when I step through the code with the debug tool everything seems to be working correctly; the method returns a different random number each loop cycle. What is going on?

   for(int i = 0; i < 5; i++)
        {
            int r = RandomNumber();
            Console.WriteLine(r);
        }

   static int RandomNumber()
        {
            Random rand = new Random();
            int x = rand.Next(1, 11);
            return x;
        }



Aucun commentaire:

Enregistrer un commentaire