0

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.

2
  • Maybe you're just really unlucky? Commented Apr 10, 2011 at 0:14
  • You stopped too soon. Keep increasing it until you reach 100. Next problem to fix is getting rid of the zeros. Commented Apr 10, 2011 at 0:34

2 Answers 2

3

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;
  //...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. your suggestion helped me find the real problem in it :)
1

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.

5 Comments

if i do that, it generates random numbers correctly, from 1 to 100. but i need that if statement. i need a 20% chance for an object to have some attributes changed...
ok, i need every object of that class, to have a 20% chance for an attribute to be true. any other suggestion of how i can do that ?
Not even asking about "what class?", i think the problem is that you do the following: create various instances of the class, each having a timer, hence all the timers build roughly simultaneously. If so, they will all generate the same numbers. You should generate the RNG once and call it's interfaces from all the objects.
no, i had a very simple error in there ... fixed it anyway. thank you.
@sorin doesnt the code you have already do that since it will only enter the if block when the number is less than or equal to 20 out of 100 (20/100) = 20%...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.