Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Produce a random number in a range using C#

Tags:

c#

.net

random

How do I go about producing random numbers within a range?

like image 593
RoR Avatar asked Oct 20 '10 06:10

RoR


People also ask

How do I generate random integers within a specific range in C?

The srand() function is used to set the starting value for the series of random integers. You can use the srand() to set the seed of the rand function to a different starting point. The parameters that are passed into the srand() function are the starting values for the rand method.

What is the range of rand () in C?

The rand function, declared in stdlib. h, returns a random integer in the range 0 to RAND_MAX (inclusive) every time you call it. On machines using the GNU C library RAND_MAX is equal to INT_MAX or 231-1, but it may be as small as 32767.


2 Answers

You can try

Random r = new Random(); int rInt = r.Next(0, 100); //for ints int range = 100; double rDouble = r.NextDouble()* range; //for doubles 

Have a look at

Random Class, Random.Next Method (Int32, Int32) and Random.NextDouble Method

like image 52
Adriaan Stander Avatar answered Sep 24 '22 00:09

Adriaan Stander


Try below code.

Random rnd = new Random(); int month = rnd.Next(1, 13); // creates a number between 1 and 12 int dice = rnd.Next(1, 7); // creates a number between 1 and 6 int card = rnd.Next(52); // creates a number between 0 and 51 
like image 32
Vishal Kiri Avatar answered Sep 24 '22 00:09

Vishal Kiri