+ 1
C# random numbers?
How to generate random numbers in console applications using c#?
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);
+ 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.
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.