Random number generator always generates 42?

Help! Here is my code:
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
//
// Danny's dice simulator
// Change the sides of the dice to get
// a random number out of your number
//
#include <cstdlib>
#include <iostream>

using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
// How many sides does your dice have?
int sides;
cout << "How many sides does your dice have?";
cin >> sides;
// Randomise out of users number
int n;
n = rand() % sides + 1;
// n is the resulting number
cout << "Your random number out of ";
cout << sides;
cout << " is:";
cout << n << endl;
// Press any key to continue
system("PAUSE");
return 0;
}

If your number of sides is less than 42, then your answer is always the number of sides.
If your number of sides is more than 42, then the answer is always 42. Help please! :(
You need to seed the random number generator by calling srand.

Call srand at the very start of your program (beginning of main). But only call it once, do not call it for each random number you want to generate.

 
srand( time(0) );
This is because rand() doesn't really produce random numbers; it produces numbers based on a (complex) mathematical formula.

Add the line srand(time(0)); to your code
Last edited on
Got an error?
 
K:\CodeBlocks\Projects\dannys-dice\main.cpp:10: error: expected constructor, destructor, or type conversion before '(' token

Bear in mind I know almost nothing about c++, and error reports make no sense to me XD
I added srand( time(0) ); in between using namespace std; and int main;.
To use time(), you need to #include <ctime>

Sorry, I forgot to mention that before
the srand call needs to go inside of main. At the start of it.
Thank-you. I have implemented both of your fixes and have fixed the program. Thanks for your time :)
Topic archived. No new replies allowed.