Sorin
Sorin

Reputation: 1

C# random number problem

I have this code which should generate numbers between 1 and 100:

int aux;
aux = Game1.rand.Next(101);
if (aux <= 20)
{
     Trace.WriteLine(aux);
     seeker = true;
}

The problem is i get values smaller than 20 every time. If i change 20 to 30 in the if statement, i always get numbers smaller or equal to 30. How can i overcome this isue? Thank you.

Upvotes: 0

Views: 298

Answers (2)

Mark Cidade
Mark Cidade

Reputation: 99957

You need to put your Trace.WriteLine(aux); before the if statement in order for it to write out any numbers above 20 (or 30, as the case may be):

int aux;
aux = Game1.rand.Next(101);
Trace.WriteLine(aux);

if (aux <= 20)
{
  seeker = true;
  //...
}

Upvotes: 3

iehrlich
iehrlich

Reputation: 3592

Try something like

int aux;
aux = Game1.rand.Next(101);
Trace.WriteLine(aux);

You get values below or equal 20 simply because you have if() clause exactly saying you need values below or equal 20.

Upvotes: 1

Related Questions