Produce a random number in a range using C#
C#.NetRandomC# Problem Overview
How do I go about producing random numbers within a range?
C# Solutions
Solution 1 - C#
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
Solution 2 - C#
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
Solution 3 - C#
Something like:
var rnd = new Random(DateTime.Now.Millisecond);
int ticks = rnd.Next(0, 3000);
Solution 4 - C#
Use:
Random r = new Random();
int x= r.Next(10);//Max range
Solution 5 - C#
For future readers if you want a random number in a range use the following code:
public double GetRandomNumberInRange(double minNumber, double maxNumber)
{
return new Random().NextDouble() * (maxNumber - minNumber) + minNumber;
}
Solution 6 - C#
Aside from the Random Class, which generates integers and doubles, consider:
-
Stack Overflow question Generation of (pseudo) random constrained values of (U)Int64 and Decimal
Solution 7 - C#
Here is updated version from Darrelk answer. It is implemented using C# extension methods. It does not allocate memory (new Random()) every time this method is called.
public static class RandomExtensionMethods
{
public static double NextDoubleRange(this System.Random random, double minNumber, double maxNumber)
{
return random.NextDouble() * (maxNumber - minNumber) + minNumber;
}
}
Usage (make sure to import the namespace that contain the RandomExtensionMethods class):
var random = new System.Random();
double rx = random.NextDoubleRange(0.0, 1.0);
double ry = random.NextDoubleRange(0.0f, 1.0f);
double vx = random.NextDoubleRange(-0.005f, 0.005f);
double vy = random.NextDoubleRange(-0.005f, 0.005f);