问题
I'm just trying to have simply RndInt(limit) function that will return random numbers with a limit as limit.
cout << "Enter higher limit of random range:" ;
cin >> limit;
while(limit != 0)
{
// RndInt(limit);
cout << "Random number smaller than " << limit << " is " << RndInt(limit) << endl;
cin.get();
cin.get();
cout << "Other random number smaller than " << limit << " is " << RndInt(limit) << endl;
cin.get();
cin.get();
cout << "There is " << RndInt(limit) << " ways I love you" <<endl ;
cout << "Enter higher limit of random range:" ;
cin >> limit;
}
return 0;
}
int RndInt(int limit)
{
srand(time(&base));
int rndnumber;
rndnumber=rand()%limit;
base+=100;
return rndnumber;
}
I'm having problem to make RndInt subsequent calls display different integer. When I debug its fine subsequent calls to RndInt(limit) give different value. But when I try to run it without cin.get() for pause I get same numbers in all three calls. I figured out that problem is that seed is in the same second.
My question is how to make calls to RndInt return different values without pause. What to do to srand function ?
回答1:
Do not call srand()
every time you want a random number. Call srand()
once at the start of your program, and then call rand()
for each number.
来源:https://stackoverflow.com/questions/11623594/srand-is-too-slow-in-c-it-return-same-number