% 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.