Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate random numbers from a range in c# [duplicate]

So I need to generate random numbers based on user set parameters, and make a basic math expression. They have 3 options; single, double, or triple digit numbers. So based on that I need to generate a random number from 0 to 9, 0 to 99, and 0 to 100.

So far I've read about the Random class. This is my poor attempt:

Random rnd = new Random();
int value = 0;

if (digits == 1)
{
    rnd.Next(value);
    q1Lbl.Text = value.ToString();
}
like image 373
Sal Avatar asked Dec 07 '25 17:12

Sal


1 Answers

You need this overload of Random.Next():

public virtual int Next(
    int minValue,
    int maxValue
)

Where:

minValue = The inclusive lower bound of the random number returned.

maxValue = The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue.

Note the words inclusive and exclusive in the parameter descriptions. This means the minimum value can be returned in the possible values, while the maximum value will not be possible.

This is further clarified in the description of the return value:

Return Value - A 32-bit signed integer greater than or equal to minValue and less than maxValue; that is, the range of return values includes minValue but not maxValue. If minValue equals maxValue, minValue is returned.

For example, to get single digit values between 0 and 9 (inclusive), you'd use:

int value = rnd.Next(0, 10); // return a value between 0 and 9 inclusive

To get double digits, you'd use:

int value = rnd.Next(10, 100); // return a value between 10 and 99 inclusive

Finally, to get triple digit numbers, you'd use:

int value = rnd.Next(100, 1000); // return a value between 100 and 999 inclusive
like image 100
Idle_Mind Avatar answered Dec 09 '25 18:12

Idle_Mind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!