OK so there are a couple different ways to generate random numbers.
The first way we can do this is to add this code:
Random randnum = new Random(); int num = randnum.Next();
So what that did was make a new random number named randnum then assigned a new variable named num equal to the random number.(we do this so we can print the number if we want.)
Now what you may have noticed is that will make a random number but you probably want your number to have a limit to do this we change the code to:
Random random = new Random(); int num = random.Next(100);
So this will generate a positive number up to 100 including 0, which is good but in some case you won't want 0 to be picked like if you where picking a raffle winner or something to that effect.
So the last and most used way is to change the code to:
Random random = new Random(); int num = random.Next(1, 100);So now it generates a number between 1 and 100.
OK so now that your know how to generate a random number lets make a dice roller to demonstrate how to use it.
So first make a new project and add a label and a button to your form.
Now double click the button and add this code:
Random random = new Random(); int num = random.Next(1, 6); label1.Text = Convert.ToString(num);then try it out.
So the code label1.Text = Convert.ToString(num); takes are variable that's equal to the random number and converts it to a string and prints it out in the label.
So there you go, now you know how to generate and print random numbers.
Hope you enjoyed this tutorial, if you have any questions just ask.:)


Sign In
Create Account


Back to top









