Randomization

• 12-14-2002
blackmagic
Randomization
I created a slot machine program which runs ok, but every time I run the program i get the same numbers randomized - could someone please tell me what i am doing wrong...by the way I am using a = 1+rand() %10 (is there a better way)
• 12-14-2002
devour89
Uhh that way will allways give you the same number when you run it!

use this I used it in my game also:

Code:

```int random(int low, int high) { srand(time(NULL)); return low + rand()%(high-low+1); }```
and then when you need a random number do:

Code:

`random (5,15); //a random number between 5 and 15`
Hope that helps

-Devouring One-
• 12-14-2002
ammar
You can use srand(time(0));
and don't forget to include <ctime>
• 12-14-2002
devour89
Ohh yeah i forgot to say that sorry... :D
• 12-14-2002
Magos
Quote:

Originally posted by devour89
Code:

```int random(int low, int high) {   srand(time(NULL));   return low + rand()%(high-low+1); }```

Eh, no! Only call srand(time(NULL)) once in your program. Not every time you retrieve a random number.
• 12-14-2002
devour89
I said that. Read it again:

and then when you need a random number do:
Code:

`random (5,15); //a random number between 5 and 15`
• 12-14-2002
Magos
Quote:

Originally posted by devour89
I said that. Read it again:

and then when you need a random number do:
Code:

`random (5,15); //a random number between 5 and 15`

If you do this:
Code:

```int main() {   for(int i=0; i<5; i++)   cout << Random(0, 10) << endl;   return 0; }```
You call Random(...) 5 times, and thus calling srand() 5 times. Not good, you should only call srand() 1!!! time in your program.
Remove it from the random function and place it in the beginning of your program instead.
• 12-14-2002
Aran
seeding the generator at every call of the random function leads to a repeating pattern.. that's why you don't want to do it.