This question already has answers here:
Closed 7 years ago.
Possible Duplicate:
rand function returns same values when called within a single function c++
Why is rand() generating the same number?
die.h
#ifndef DIE_H
#define DIE_H
class Die
{
private:
int number;
public:
Die(){number=0;}
void roll();
int getNumber()const{return number;}
void printValue();
};
#endif
die.cpp
#include"die.h"
#include<iostream>
#include<time.h>
using namespace std;
void Die::roll()
{
srand(static_cast<int>(time(0)));
number=1+rand()%6;
}
void Die::printValue()
{
cout<<number<<endl;
}
main.cpp
#include"die.h"
#include<iostream>
using namespace std;
int main()
{
Die d;
d.roll();
d.printValue();
d.roll();
d.printValue();
d.roll();
d.printValue();
}
Your calls to die.roll()
are so close together that time(0)
is actually returning the same value every time, and, thus, your rand seed is the same for each call to .roll()
.
Try calling srand(static_cast<int>(time(0)));
once (and only once) outside of .roll()
(like in the Die constructor or main()
).
You need to initialize the random generator with a "truly random" (or at least unique) seed, and do it only once.
This is usually done with srand(time(NULL))
at the beginning.
Numbers generated by rand()
are not random, they are *pseudo*random: given the same seed, it will always return the same sequence. By default, I believe the initial seed is zero (however, it is for sure always the same between program runs - so without seeding you'll always get the same apparently random sequence every time).
As emartel pointed out, the only real change you need is to call time(NULL)
instead of time(0)
.
Alternately you could call srand(time(NULL))
in the constructor and then just use rand()
in roll()
.