Using rand() function and resetting the seed?

So I've actually used rand() happily without any problems so far, but now I faced a problem. I have an AI loop that initialized a random number between 1 and 2 at the beginning, so something like this:

1
2
3
4
5
6
7
8
9
10
11
12
while (condition)
{
   int random = rand()% 1 + 2;
   if (random == 1)
   {
      //code
   }
   else
   {
      //code
   }
}


So this doesn't really work since it doesn't actually assign a new random value. I came across srand(time(NULL)), which resets the seed, but I didn't quite get when to use it. Do I have to call it in every cycle of the loop? I'm not completely sure how this works.
% gives you the remainder after a division. IE: 7%3 == 1 because 7/3 has a remainder of 1

Look again at your formula:

rand()% 1 + 2;

You're doing % 1. Any number divided by 1 will have a remainder of 0. So rand() % 1 will always be 0. Which means rand() % 1 + 2 will always be 2.


If you want to pick between 1 or 2 randomly, you probably want: rand() % 2 + 1. IE, the %2 gives you either 0 or 1.... which you add 1 to, giving you either 1 or 2.


srand(time(NULL)), which resets the seed, but I didn't quite get when to use it.


Typically you would use it once at the very start of your program. rand() is effectively a mathematical formula that takes an input number and "scrambles" it to produce a seemingly random output number. It then uses that output number as the next input number.

srand() produces the very first input number... effectively giving rand() a starting point. By seeding with the current time, you ensure you have a different starting point each time the user launches your program.



However if you seed with the time each time you generate a random number with rand(), it would be counter productive. So...

Do I have to call it in every cycle of the loop?


absolutely not.
Oh, I didn't even notice that. Yeah, I wanted to pick a number between 1 and 2, but apparently I put the in the wrong order. Problem solved.
Topic archived. No new replies allowed.