Sunday, May 10, 2009

Random number generator in c++?

I created a number guessing game using c++. But for some reason it always generates the same numbers every run time.


How can this be fixed.

Random number generator in c++?
you should call the function srand() each time before rand() to create a different sequence of numbers.





you should include cstdlib.h header file


#include %26lt;cstdlib%26gt;


using std::srand;





srand() receives an integer as argument, for each integer passed to it, rand() will generate a different sequence.





you can pass the time of system to srand() like this:


srand( time(0) );


and of course you will have to include time.h header file in your source code.
Reply:this all programing, not too good with programming





sorry
Reply:You must "seed" the random number generator in order to get different random numbers out of rand(). The seed should be different for each program execution, and an easy way to do this, is to seed it with the time. Note that if you execute this program twice in the same second (unlikely), you will get the same value as the seed will not change.





Example:


#include%26lt;cmath%26gt;


#include%26lt;iostream%26gt;


#include%26lt;ctime%26gt;





int main()


{


srand(time(0));


std::cout %26lt;%26lt; rand() %26lt;%26lt; std::endl;


return 0;


}

phone cards

No comments:

Post a Comment