Tutorials Navigation
[C#] Random number tutorial
Tutorial Name: [C#] Random number tutorial
Category: PC Tutorials
Submitted By: Skittle
Date Added:
Last Updated:
Comments: 1
Views: 2,576
Related Forum: PC Building Forum
Share:
In this tutorial I will show you how to generate random numbers and use them.
For my example, I will create a function that simulates a dice roll so when it is called, a random number between 1 and 6 is returned. First, lets create our variable that will be used to generate the random number:
Random rnd = new Random();
If you are thinking "If I want to generate multiple random numbers, do I need the same amount of random variables? No, you only ever need one random variable to generate as many random numbers as you want. Here is the code to generate a random number:
int min = 1; //minimum number
int max = 7; //maximum number + 1
rnd.Next(min, max); //random number generated
This will give us a number from and including 1 To 6. If the max variable is set to 6, the highest number we can generate is 5, this does not apply the the minimum number.
Now, we need to assign our random number to a variable and return it from our function, here is the code to finish the job:
int num = rnd.Next(min, max);
return num;
After we put all of our code together, we should finally have this:
private int RollDice()
{
Random rnd = new Random(); //variable used to generate the random number
int min = 1; //minimum number
int max = 7; //maximum number + 1
int num = rnd.Next(min, max); //random number generated
return num;
}
If you found this tutorial useful, any Rep is greatly appreciated
If you need any help with this, feel free to PM me
Ratings
Comments
Related Tutorials
- 01. Emulating Xbox 360 on PC for Running COD4 With Mods(3,709)
- 02. How to: Matrix Numbers | Batch File(1,964)
- 03. How to Password Protect Files on Windows(874)
- 04. How to play Socom 2/3/ and Combined Assault on PC(6,937)
- 05. Modern Warfare 2 Vac Ban Bypass Tutorial(6,282)
- 06. How to embed an image on TheTechGame(3,151)
- 07. [PC] NIOH 2 OTHER USER SAVE RESIGN(13,104)
- 08. Host bot lobbies! Full Tutorial!(11,676)
- 09. Unban yourself [Plutonium BO2](14,328)
- 10. Fall Guys - How to Change Your Name Color on Fall Guys(8,422)
- 11. Best Crosshair Settings for Valorant(6,565)
- 12. Othercide The Surgeon Boss Guide(2,577)
- 13. Othercide Remembrances Unlock Guide(4,529)
- 14. Othercide Beginners Tips and Tricks(2,746)
- 15. How to Fix Grounded Crashes, Loading Time, Low FPS and Other(4,899)
"[C#] Random number tutorial" :: Login/Create an Account :: 1 comment