+ 1

C# random numbers?

How to generate random numbers in console applications using c#?

13th Dec 2016, 9:17 AM
Nikolai Russev
Nikolai Russev - avatar
3 Antworten
+ 7
// First line creates a new Random object // Second line returns a random number Random rand = new Random(); int x = rand.Next(5); // 0 <= x < 5 int y = rand.Next(6,9); // 6 <= y < 9 Console.WriteLine(x); Console.WriteLine(y);
13th Dec 2016, 9:31 AM
Jafca
Jafca - avatar
+ 5
The Random object is needed to generate a random number, specifically the .Next(upperLimit) method of the Random class. If you create int rand, rand will only be able to hold an integer value that it is given; it won't generate a random number for itself.
13th Dec 2016, 11:32 AM
Jafca
Jafca - avatar
0
Hi, my question is why is it necessary to initialize new rand object instead of just creating a variable int rand . To be specific, Random rand = new Random(); part is the one that I'm confused about.
13th Dec 2016, 11:18 AM
Steve