Tutorials Navigation

Tutorials :: New :: Popular :: Top Rated

Tutorials: 18,357 Categories: 12

Total Tutorial Views: 42,410,182

[C#] Random number tutorial

Tutorial Name: [C#] Random number tutorial  

Category: PC Tutorials

Submitted By: Skittle

Date Added:

Last Updated:

Comments: 1

Views: 2,574

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

Current rating: 2.50 by 6 users
Please take one second and rate this tutorial...

Not a Chance
1
2
3
4
5
6
7
8
9
10
Absolutely

Comments

"[C#] Random number tutorial" :: Login/Create an Account :: 1 comment

If you would like to post a comment please signin to your account or register for an account.

HaloPosted:

You made is seem pretty easy to understand this, nice tutorial!