Visual C# 2005 Guide
In C#, we can generate pseudo-random numbers using the Random class. To start, declare a new instance of the Random class in the following way,
Random randomNumber = new Random();
The following statement would make the variable myRandomNumber equal to an integer from 0 to 9,
int myRandomNumber = randomNumber.Next(10);
Another version of the Next method allows you to specify a range for your number. The following will generate a number from 0 to 9. The first number is the lowest value, the second number is one more than the highest,
int myRandomNumber = randomNumber.Next(0, 10);
There is also the NextDouble() method. It returns a double greater than or equal to 0 and less than 1.0.
double myRandomNumber = randomNumber.NextDouble();
Having A Go
- Use the explanation above to generate 6 lottery numbers. Your program may generate duplicates but you can skip ahead in the guide to work out how to avoid this.
- Write a program to simulate the rolling of 2 dice.