Generating Random Numbers in C#
In C#, we can use many ways to generate random numbers. It is very easy when we use the in-built methods from C#.
1. Generating a Random Integer:
The below code snippet generates a random integer between 0 and Int32.MaxValue
.
Random random = new Random();
int randomNumber = random.Next();
2. Generating a Random Integer within a Specified Range:
This method generates a random integer between 1 (inclusive) and 100 (exclusive)
Random random = new Random();
int randomNumberInRange = random.Next(1, 100);
3. Generating a Random Double:
This method generates a random double between 0.0 and 1.0
Random random = new Random();
double randomDouble = random.NextDouble();
4. Generating a Random Double within a Specified Range:
You can scale and shift the result of random.NextDouble()
to fit a specific range and it generates a random double between min and max
Random random = new Random();
double min = 5.0;
double max = 10.0;
double randomDoubleInRange = random.NextDouble() * (max - min) + min;
Simple Program with all the above methods:
using System;
class Program
{
static void Main()
{
Random random = new Random();
// Method 1: Generate a random integer
int randomInt = random.Next();
Console.WriteLine("Random Integer: " + randomInt);
// Method 2: Generate a random integer within a specified range
int randomIntInRange = random.Next(1, 100);
Console.WriteLine("Random Integer between 1 and 100: " + randomIntInRange);
// Method 3: Generate a random double
double randomDouble = random.NextDouble();
Console.WriteLine("Random Double: " + randomDouble);
// Method 4: Generate a random double within a specified range
double min = 5.0;
double max = 10.0;
double randomDoubleInRange = random.NextDouble() * (max - min) + min;
Console.WriteLine("Random Double between 5.0 and 10.0: " + randomDoubleInRange);
Console.ReadKey();
}
}
Output:
Random Integer: 1275583585
Random Integer between 1 and 100: 43
Random Double: 0.36879271332584
Random Double between 5.0 and 10.0: 9.30931732492024
Comments (0)