Random numbers as objects

G

Guest

Hello,

I have created a class called Die and an implementaion of Die (ex. to
follow) where the default generates a NEW digit 1-6.

I am creating a dice game wherein: a die is rolled (Roll_ 1) then the user
is asked to guess if Roll_2 will be higher or lower than Roll_1.

Without showing the rest of this riduclous project, my issue is that the new
objects Roll_1 & Roll_2 are the same number in the comparison.

However, when I go through the game a second time (the user can play again),
a different number is generated for Roll_1, yet again Roll_2 is the same.

Implemenation code:
Die::Die() {
int roll;
srand((unsigned int)time(0));
do {
roll = 1 + rand()%6;
}while (roll <= 0);
Set_FaceUp(roll);
}

Driver Code:
Die Roll_1;
Die Roll_2;

Any advice would be appreciated, I'm stuck! Thanks
 
D

David Harmon

Die::Die() {
int roll;
srand((unsigned int)time(0));

You should never be calling srand() more than once per execution of your
program. Put the srand() call at the beginning of main() and omit it
elsewhere.

The usual answer to that is the same in C++ as it is in C, and is
covered in Steve Summit's C FAQ. It is always good to check the FAQ
before posting. You can get the FAQ at:
http://www.eskimo.com/~scs/C-faq/top.html

For a better random number generator see http://www.boost.org or
Stroustrup chapter 22.7.
 
M

mchoya

Thank you, thank you - I was not able to move the duplicitous srand, but I
was able to follow the links where I found better code for random numbers.

(FYI - I used (int)((double)rand() / ((double)RAND_MAX + 1) * N) - where n
is the max number (6))
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,161
Messages
2,570,892
Members
47,431
Latest member
ElyseG3173

Latest Threads

Top