Generate a random number in a range using C#
This post will discuss how to generate a random number in a range using C#.
1. Using Random.Next() method
The Random.Next() method is commonly used to generate a pseudo-random random integer between the specified range. Its usage is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; public class Example { /* * minValue: inclusive lower bound * maxValue: exclusive upper bound */ public static int generateRandInt(int minValue, int maxValue) { Random r = new Random(); return r.Next(minValue, maxValue); } public static void Main() { // generate a random number between 1 and 5 int r = generateRandInt(1, 6); Console.WriteLine(r); } } |
Note that the minValue is inclusive, and maxValue is exclusive. If minValue is skipped, the Next() method returns a non-negative random integer that is less than maxValue.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; public class Example { // Returns a non-negative random number less than `maxValue` public static int generateRandInt(int maxValue) { Random r = new Random(); return r.Next(maxValue); } public static void Main() { // generate a random number between 0 and 6 int r = generateRandInt(7); Console.WriteLine(r); } } |
2. Using Random.NextDouble() method
If you need to generate a random floating-point number in a range, consider using the Random.NextDouble() method instead. It returns a random floating-point value greater than or equal to 0.0, but less than 1.0. This method can be extended to generate values in any range, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; public class Example { // Returns a double value greater than or equal to `minValue`, and less than `maxValue` public static double generateRandInt(int minValue, int maxValue) { Random r = new Random(); return r.NextDouble() * (maxValue - minValue) + minValue; } public static void Main() { // generate a random number between 2.0 and 3.9999999999999999 double r = generateRandInt(2, 4); Console.WriteLine(r); } } |
If minValue is skipped, the solution returns a double value greater than or equal to 0.0, and less than maxValue.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; public class Example { // Returns a double value greater than or equal to 0.0, and less than `maxValue` public static double generateRandInt(int maxValue) { Random r = new Random(); return r.NextDouble() * maxValue; } public static void Main() { // generate a random number between 0.0 and 6.9999999999999999 double r = generateRandInt(7); Console.WriteLine(r); } } |
That’s all about generating a random number in a range using C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)