Trouble with generating a random number

Hello! I am having trouble getting a pseudo-random number generator working. The idea is to pick a number between 1 and 999, then print it. This code using the clock as a seed for the random number generator, so I get a different number each time I use it.

I am getting the error messages:
error C2062: type 'unsigned int' unexpected
error C2065: 'seed' : undeclared identifier
error C2065: 'seed' : undeclared identifier

Here's the code-
// Start of code
#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int DrawNum (int);

int main()
{
const int MIN = 1;
const int MAX = 999;
int numDrawn,

unsigned int seed;

seed = static_cast<unsigned>(time (NULL));
srand (seed);

numDrawn = DrawNum (MAX);
cout << numDrawn;
return 0;
}
int DrawNum (int max)
{
double x = RAND_MAX + 1.0;
int y;

y = static_cast<int> (1 + rand() * (max / x));
return (y);
}
//end of code
Any help would be greatly appreciated!
try to add a semicolon instead of comma after int numDrawn
Well that was dumb mistake! Thanks.
Now there is another problem,
If I run the program consecutively, it just seems to add a number. For example, running it 3 times has printed out
752
753
754
I think it has something to do with the clock, but no real idea how to fix it. I would want a more "random" spread, such as
589
210
745
Any ideas?
Maybe the reason for the closely related numbers is because you produce random number by executing the program ( not by a loop ), causing srand() to be called also and seed closely related numbers, since the value returned by time() is only seconds interval to the previous one :

if you will run it in a loop, it will get more "random" :

This program produce 20 random numbers in the range 1 - 999

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>	
#include <ctime>	
#include <cstdlib>	

int main ()
{
    srand( time( NULL ) );
    
    const int MIN = 1;
    const int MAX = 999;
    
    for ( int i = 0; i < 20 ; ++i ) {
        std::cout << unsigned( rand() % ( MAX - MIN ) + MIN) << std::endl;
    }
}


sample output:

290
490
759
558
754
562
25
675
606
247
4
180
959
683
99
512
970
29
703
623


Hope this helps
Last edited on
Topic archived. No new replies allowed.