Random Generator.

Hey guy. I need some help with a random number generator.

I looked through the post, and found this random generator but for some reason it didn't work out very well.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream> 
#include <string> 
using namespace std; 

int randomizer(){
	int n(0);
	srand((unsigned)time(NULL));
	n=rand();
	n %= 10;
	n++;
	return(n); 
} //randomizer. 

int main() {
	for(int i = 0; i != 100; i++){
		cout << randomizer(); 
	}//for.
}//main.  


for some reason when I run the code, and even though it generate a random number, it only do it once, everything else after that is the same as the first one. Is there another random generator that I can put into the same format as the code above, but generate different number. Thx.
You only need to call srand((unsigned)time(NULL)); once. If you call it right before every random it always have the same results. Put it in main and it will fix your problem.
you also forgot to include the "ctime" that is necessary for the time()
#include <ctime>

[EDIT]
The problem actually is that when you call srand() you give it a seed to create the random number. Because of the speed the program is executed this seed returned form (srand((unsigned)time(NULL)) is gonna be the same (or almost the same) all the time (in the same execution). That way you give to srand() the same seed every time, something that has as a result to produce the same random number.
If you put the (srand((unsigned)time(NULL)) at the beginning of the main() you give to srand() a new seed each time the program is executed and you produce the random numbers depending on that.

Hope that helps
Last edited on
Oh, it works out beautifully. Thx Mitsakos.
can anyone post the final code after modification

I use turbo c++ v3.0 or c-free v4.0.
thanks
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream> 
#include <string> 
using namespace std; 

int randomizer(){
   int n(0);
   n=rand();
   n %= 10;
   n++;
   return(n); 
} //randomizer. 

int main() {
   srand((unsigned)time(NULL));
   for(int i = 0; i != 100; i++){
      cout << randomizer(); 
   }//for.
}//main.  

As I saied before, you just move srand((unsigned)time(NULL)); at the beginning of the main (or in general somewhere before your first execution of the rand, but where it can only called once)
Thanks
sorry I was not bright enough to understand the explanation
Topic archived. No new replies allowed.