I was using rand() to produce some random numbers inside a function to populate some arrays but when I ran the program I noticed it was giving always the same row of generated numbers. The arrays were filled with the same row of generated numbers, it could be all 0 or a row with different numbers, but this pattern of numbers were the same in every array.
So I used debug to run the program step by step and it worked, rand() were generating different numbers to every array..
After this I decided to try another method to generate random numbers. I found a way to do this using Boost library.
This is the code I'm using now:
int main(){
typedef boost::mt19937 RNGType;
RNGType rng( (unsigned int)time(NULL));
boost::uniform_int<> one_to_six( 1, 6);
boost::variate_generator< RNGType, boost::uniform_int<> >
dice(rng, one_to_six);
for(int i=0;i<10;i++){
std::cout<<dice()<<std::endl;
}
}
If I use this code on main() function, everything goes well and it gives me 10 random numbers. But if I put this code in a function to call it whenever I want it returns me the same number. Always 55555555, or 0000000.. Fun fact is, if I use debug and make a breakpoint at that function and run it step by step, it works again giving me always different numbers. So I don't know what I'm missing here..
edit: When I used rand() I was using srand((unsigned int)time(NULL));
Aucun commentaire:
Enregistrer un commentaire