I want c++ generate random number is repeat -


i 2 week newbie programming in c++ having challenge code work desired. goal generate non repeated random number. here part of code,

unsigned long seed = time(null); int gsmnun (int l, int h) {     srand(seed);     int user_phone = rand()%h+l;      return user_phone; }  int main() {      int z = gsmnun(70000000, 99999999);     for(int i=0; i<20; i++)     {         cout << "the random number is!" << z << endl;     }      return 0; } 

you're reseeding random number generator each time function called same seed, you're going same random number rand().

i've modified code , added comments, please note seed random number generator once when application starts , calls rand() produce actual random numbers.

reseeding generator should not done each time want new random number, calls made result in same numbers being generated iterations.

unsigned long seed = time(null);  int gsmnun (int l, int h)  {  // removed srand() here.  int user_phone = rand()%h+l;   return user_phone;  }   int main()  {   srand(seed); // seed @ application start   for(int i=0; i<20; i++)     {   int z = gsmnun(70000000, 99999999);     cout << "the random number is!" << z << endl;     }  return 0; } 

Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -