Reputation: 859
I'm trying to generate a bunch of random numbers using rand() % (range). Here's how my code is setup :
srand(time(NULL));
someClass *obj = new someClass(rand()%range1,rand()%range2... etc ); // i.e. a number of random numbers one after the other
Whenever I run this, it seems all the calls to rand() generate the same number. I tried doing it without the : (edit : all rand() do not generate the same number it seems , read edit at the end)
srand(time(NULL));
then , every execution of the program yields the same results.
Also, since all calls to rand() are in a constructor , I cant really reseed it all the time. I guess I can create all objects sent to the constructor beforehand and reseed the random number generator in between, but it seems like an inelegant solution.
How can I generate a bunch of different random numbers ?
edit: It seems because I was creating a lot of objects in a loop, so every time the loop iterated srand(time(NULL)) was reseeded and the sequence got reset ( as time(NULL) has a resolution of a second) , that's why all subsequent objects had very similar properties.
Upvotes: 3
Views: 2772
Reputation: 11787
check this code at: http://ideone.com/xV0R3#view_edit_box
#include<iostream>
#include <stdio.h>
#include <stdlib.h>
#include<time.h>
using namespace std;
int main()
{
int i=0;
srand(time(NULL));
while(i<10)
{
cout<<rand()<<endl;
i++;
}
return 0;
}
this produces different random numbers. you need to call srand()
only once. rand() generates a different number every time after the srand()
call
Upvotes: 1
Reputation:
Call srand once at the begin of the program. Then call rand()%range any time you want a random number. Here is an example for your situation, that works pretty well
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
class Test
{
public:
Test(int num0,int num1, int num2):num0_(num0),num1_(num1),num2_(num2){}
int num0_,num1_,num2_;
};
int main()
{
srand(time(NULL));
Test *test=new Test(rand()%100,rand()%100,rand()%100);
cout << test->num0_ << "\n";
cout << test->num1_ << "\n";
cout << test->num2_ << "\n";
delete test;
return 0;
}
Upvotes: 2
Reputation: 247969
If you call srand
once, then all subsequent rand
calls will return (different) pseudorandom numbers. If they don't, you're doing it wrong. :)
Apart from this, rand
is pretty useless. Boost.Random (or the C++11 standard library <random>
header) provides much more powerful random number generators, with nicer, more modern interfaces as well (for example allowing you to have multiple independent generators, unlike rand
which uses a single global seed)
Upvotes: 7
Reputation: 92261
Unless reseeded with a different starting point, rand()
always returns the same sequence. That is actually a feature to make program tests repeatable!
So, you have to call srand
if you want a different sequence for different runs. Perhaps you can do that before calling the first constructor?
Upvotes: 2