Rifki
Rifki

Reputation: 901

Control over random numbers in C#

If I use two random numbers, how can I ensure that the first of these numbers generated is always larger than the second in order to present a subtraction or a divide quiz to the user?

Upvotes: 2

Views: 698

Answers (4)

Konstantin Spirin
Konstantin Spirin

Reputation: 21271

var max = 1000;
var rnd = new Random();
int a, b;
do
{
    a = rnd.Next(max);
    b = rnd.Next(max);
} while (a <= b);

You can use similar approach for more complex conditions too (for example if your task is to generate 2 numbers that in sum give more than 100, etc).

You will have to make your code smarter if probability of random numbers satisfying your condition is so small that generation takes too much time but for this particular task this approach is good enough.

Upvotes: 1

Leo Chapiro
Leo Chapiro

Reputation: 13984

You generate the second random number and add it to the first one.

Upvotes: 2

SEngstrom
SEngstrom

Reputation: 321

You can generate numbers like this (pseudocode): (int)(a*rand()+b) where a and b control the range and starting point of your random numbers.

If a1=10, b1=1 for instance you get a range of 1-10. With a2=10 and b2=11 you get numbers in the range 11-20, which might be good for simple subtraction problems.

Upvotes: 0

Oded
Oded

Reputation: 498914

You don't.

Just check which one is larger and present accordingly.

Upvotes: 9

Related Questions