srand doesn't replace rand, they both need to be used.
what rand() does is use an algorithm to generate a random number. The problem is that the algorithm is always the same, so the random number generated is always the same.
What you need is a way to "seed" that algorithm with a different number each time, so that rand() will generate a different number.
The time(0) function returns the number of seconds that has elapsed since midnight, Jan 1, 1970. Every second, the value of time(0) will change, giving you a perfect way to seed the random number generator with a different value each time you run your program.
Once and only once in your program, and before you use rand(), you should insert the line:
srand(time(0));
This will seed the generator, so that your rand() call will always give you a good approximation of a random number.
You have another problem. Your for loop doesn't test if the number is more than 20000, it generates 20000 random numbers. What you should do is use a while loop which tests the value of the random number, and only exits when the number is greater than 20000, like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include <ctime>
srand(time(0));
int number=1; //start with a value less than 20000
int count=1;
while (number<20000)
{
number = rand()%maxrange; // generate a random number
//between 0 and whatever max you want
count++; //increase loop count
}
cout << "number is" << number;
cout << "generated on try #: " << count;
|
when I run it with maxrange = 25000 I get:
23315 was generated on try :7