Question

Possible Duplicate:
Same random numbers every loop iteration

Here is my code:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int attack() {
    srand((unsigned)time(NULL));
    int hits=0;
    for (int i=0;i<=3;i++) {
        int a = rand() % 6;
        if (a==6 || a==5)
        {
         hits++;   
        }
    }
    return hits;
}

int main () {
    int a=attack();
    cout << a << endl;
    int b=attack();
        cout << b << endl;
    int c=attack();
        cout << c << endl;
    int d=attack();
        cout << d << endl;
    int e=attack();
        cout << e << endl;
    int f=attack();
        cout << f << endl;
    int g=attack();
        cout << g << endl;
    int h=attack();
        cout << h << endl;
}

why are all my variables in main() the same number?

I only get outputs like this:

1
1
1
1
1
1
1
1
Was it helpful?

Solution

srand() should be called once at the start of the program (well, at some point before you start calling rand() anyway).

By calling it every time you enter the function (in quick succession), you're resetting the seed value to the same thing, which is why you're seeing duplicate numbers.

Note that you may occasionally get a different number if the time clicks over to a new second while your program is running, but it's not that likely since that particular program should finish in far less than one second.

Move the srand() call to main() before the first call to attack().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top