Sep 12, 2011 at 1:38am UTC
I'm trying to simulate rolling a dice, but every time the "random" number is 6. What am I doing wrong? Please help!
This is what I have:
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <ctime>
using namespace std;
int die()
{
return ((rand() % 6) + 1);
}
//////////////////////////////////////////////////////////
int main()
{
int num;
int die;
die=(int)(rand()%6+1);
cout << "What is your prediction? " << endl;
cin >> num;
if ((num >= 1) && (num <= 6)) {
srand((unsigned)time(0));
cout << die << endl;
}
if ((num==die)) {
srand((unsigned)time(0));
cout << die << endl;
cout << "You were correct. " << endl;
}
else if (num > 6 || num < 0) {
cout << "\n Invalid input. \n" << endl;
}
system("PAUSE");
return(0);
} // end main
Sep 12, 2011 at 2:32am UTC
You need to seed the random number generator, the easiest is to use the current time. Place this anywhere before you call rand (only needed once): srand(time())
You have the required headers, time() needs ctime, srand(int) needs cstdlib.
Sep 12, 2011 at 3:14am UTC
I ran the code and kept getting the same result too. I fixed it by adding the command in bold:
1 2
srand(time(0));
die=(int )(rand()%6+1);
Works fine now.
p.s Make sure to run it 'before' you roll the dice (create the random number).
* edit *
I had a little time to play around and streamline some stuff in the program if you're interested:
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
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <ctime>
using namespace std;
int dice()
{
return ((rand()%6)+1);
}
int main()
{
int num;
int die;
srand(time(0)); // Seed random generator
die = dice(); // Call dice function
cout << "\nWhat is your prediction? " ;
cin >> num;
if (num==die)
{
cout << "\nYou guessed correct!" ;
}
else if (num < 7 && num > 0)
{
cout << "\nYou are incorrect." ;
}
else
{
cout << "\nInvalid input." ;
}
cout << "\nThe number rolled was: " << die << endl;
system("PAUSE" );
return (0);
} // end main
I'm still new myself so if anyone can improve upon that feel free.
Last edited on Sep 12, 2011 at 3:56am UTC