C++ Random Number Generation
CMPC :: Computing :: Programming :: C++
Page 1 of 1
C++ Random Number Generation
To begin with in c++ before you can ask for a random number, you need to seed your random number generator. You can seed your random number generator by using the srand() function. For every different seed value used in a call to srand, the pseudo-random number generator can be expected to generate a different succession of results in the subsequent calls to rand. Two different initializations with the same seed, instructs the pseudo-random generator to generate the same succession of results for the subsequent calls to rand in both cases. The standard way of seeding the random number generator is by using time.
You can use this functon call to do so:
You can copy and save these into a header file for your own use or you can write your own versions of them.
You can use this functon call to do so:
- Code:
srand(time(NULL));
- Code:
#include <ctime>
- Code:
#include <iostream>
#include <ctime>
using namespace std;
int myRand()
{
srand(time(NULL)*rand());
return rand();
}
int myRand(int max)
{
srand(time(NULL)*rand());
return rand()%(max+1);
}
int myRand(int min, int max)
{
srand(time(NULL)*rand());
return (rand()%(max+1))+min;
}
You can copy and save these into a header file for your own use or you can write your own versions of them.
Paul- Pickaxe
- Posts : 611
CMPC :: Computing :: Programming :: C++
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum
|
|