Roll the Dice (keep getting 6)

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
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.
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
heres what i use to get random numbers:

1
2
3
4
5
6
7
8
9
10
11
long rndnum(long lwoest,long highest)
{
     if(highest - lowest +1)
     {
             return((rand()%(highest-lowest+1))+lowest);
     }
     else
     {
             return(lowest);
     }
}


works pretty good, you cold use it like so:

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
int main()
{
	int num;
	int die;

	die = rndnum(1,6);
		
	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  

Topic archived. No new replies allowed.