mercredi 18 février 2015

Troubles with a random number generator [duplicate]


This question already has an answer here:




I have a class that represents a checking account, and in the checking account there is a class member that represents an account number. This account number is initialized in the constructor (random numbers obviously) for several different objects.I am having difficulties getting different numbers for each object. Mainly because I am just starting out in C++ and I implemented this RNG idea via several posts I have viewed here on SO.


Here is my constructor:



CheckingAccount::CheckingAccount(const Customer& owner): Account(owner){
srand ( time(NULL) );
int acctStartNum = 9;
int firstDigit = rand() % 10;
int secondDigit = rand() % 10;
int thirdDigit = rand() % 10;
int fourthDigit = rand() % 10;

ostringstream oss;
oss << acctStartNum << firstDigit << secondDigit << thirdDigit << fourthDigit;
accountNumber = stoi(oss.str());

}


I understand srand() seeds the random numbers to provide a nice spread of values each time. But when I had excluded it from my code, each object had a different accountNumber. The catch though was, that each time I ran my program the values never changed(i.e. it generated random values for each object only once and then kept those values), which is why I implemented srand(), but now all objects have the exact same accountNumber, granted they change each time I run the program. What is the deal here? Why were they all differnet before I implemented srand() and never change, but now they change but apply to all objects? Also just as a side note, I know this may look quite sloppy, but this is for an assignment that instructs me to do this IN the constructor, otherwise I'd make a function.





Aucun commentaire:

Enregistrer un commentaire