3

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();
}
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Sal
  • 59
  • 1
  • 1
  • 7

3 Answers3

9

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
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40
3
Random rnd = new Random();
int single = rnd.Next(1, 10);  // 1 ~9
int double = rnd.Next(1, 100);    // 1~99
int triple = rnd.Next(1,101);      // 1~100

loop it if you want to achieve the values multiple times

Hank
  • 187
  • 1
  • 1
  • 13
0

There's an overload of the Next method, you only have to pass the range:

Random rnd = new Random();
rnd.Next(1,20); //Gives you a number between 1 and 20

Here you find the entire documentation https://www.google.com.co/search?q=next+random+c%23&oq=next+random&aqs=chrome.1.69i57j0l5.3144j0j7&sourceid=chrome&ie=UTF-8

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
Gabriel Castillo Prada
  • 4,114
  • 4
  • 21
  • 31
  • 2
    Not quite...that'll return numbers between 1 and 19 (inclusive). The value of 20 will **not** be included in the possible return values. – Idle_Mind May 09 '17 at 00:32
  • Oh thanks guys, that clear it up a lot! Thanks a ton – Sal May 09 '17 at 00:35