Random produces same data for each object

Feb 5, 2014 at 9:05pm
I'm trying to do this exercise, which is to make 5 bunny objects for beginning,and each needs to be male or female,and according to it's sex, it receives male or female name.
Names and sex should be random.

My problem is that despite of the way I'm using to create new objects, each object receive the same name and sex. What could be the problem?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;


int GetRandom(int x){
    srand(time(0));
    return rand()%x;
}

class Bunny{

private:
    string F_names[5]={"Hajra","Mejra","Pemba","Muska","Zulfa"};
    string M_names[5]={"Baho","Mujo","Suljo","Hamo","Faho"};
    string colors[4]={"white","brown","black","spotted"};
    bool Sex[2]={true, false};
    string name;
    string color;
    int age;
    bool isMale;
    string sex;
    bool isVampire;

public:

    Bunny * next;
    Bunny()
    {
        
        isMale=Sex[GetRandom(2)];
        if(isMale)
        {
                name=M_names[ GetRandom(5)]; sex="Male";
                cout<< "Bunny "<<name<<" was born!"<<endl;
        }
        else
        {
                name=F_names[ GetRandom(5)]; sex="Female";
                cout<< "Bunny "<<name<<" was born!"<<endl;
        }
    }

};



int main()
{

    Bunny bunniesFive[5];
    Bunny HHH;
    cout << "Hello world!" << endl;
    return 0;
}
Feb 5, 2014 at 9:18pm
You should call srand() once to seed the PRNG, then call rand() to get the next number in the sequence.
Feb 5, 2014 at 9:18pm
srand uses the argument passed to it to generate a pseudo-random number that rand then bases all of it's values off of. Because you are re-initializing srand at every call to "GetRandom()" and you are seeding it with the current time, which doesn't change in the amount of time it takes to run this program, you are effectively resetting this random number.
Feb 5, 2014 at 9:21pm
Fixed. Thank you.
Feb 5, 2014 at 9:23pm
I suggest an enumerated type for their sex instead of a string.
http://www.cplusplus.com/doc/tutorial/other_data_types/
Topic archived. No new replies allowed.