Random numbers
-
Hello ! I would like to produce random numbers between 0 and 15. I tried to use srand and rand. So I used a similar code:
#define RAND_MAX 15 //Outside of the function srand(1); int Random = rand();
But the numbers are greater than 15 :confused: How can I do that ? Thanks -
Hello ! I would like to produce random numbers between 0 and 15. I tried to use srand and rand. So I used a similar code:
#define RAND_MAX 15 //Outside of the function srand(1); int Random = rand();
But the numbers are greater than 15 :confused: How can I do that ? ThanksJust #defining your own RAND_MAX is no good. The rand() method uses the RAND_MAX that was defined when the library it was in was compiled. To get it into a particular range try something like:
int Random = rand()*(15/RAND_MAX);
The other thing to note is that if you always seed the random number generator with the same number (1 in your example), it will always generate the same sequence of pseudorandom numbers. Try something like:srand( (unsigned)time( NULL ) );
This seends the generator with a value based on the current time so it should give you different sequences. Mike -
Just #defining your own RAND_MAX is no good. The rand() method uses the RAND_MAX that was defined when the library it was in was compiled. To get it into a particular range try something like:
int Random = rand()*(15/RAND_MAX);
The other thing to note is that if you always seed the random number generator with the same number (1 in your example), it will always generate the same sequence of pseudorandom numbers. Try something like:srand( (unsigned)time( NULL ) );
This seends the generator with a value based on the current time so it should give you different sequences. MikeThanks ;)
-
Hello ! I would like to produce random numbers between 0 and 15. I tried to use srand and rand. So I used a similar code:
#define RAND_MAX 15 //Outside of the function srand(1); int Random = rand();
But the numbers are greater than 15 :confused: How can I do that ? ThanksTo produce random numbers from 0 to some predefined limit it would probably be easiest to do: #define RAND_MAX_LIMIT 15 // Set 15 as limit for randomly generated values srand((unsigned)time(NULL)); // Seed random number generator with current time int Random = rand() % (RAND_MAX_LIMIT + 1); // Only generate numbers between 0 and your predefined limit
-
Hello ! I would like to produce random numbers between 0 and 15. I tried to use srand and rand. So I used a similar code:
#define RAND_MAX 15 //Outside of the function srand(1); int Random = rand();
But the numbers are greater than 15 :confused: How can I do that ? Thankscedric moonen wrote: I would like to produce random numbers between 0 and 15. Try
rand() % 16
.
"When I was born I was so surprised that I didn't talk for a year and a half." - Gracie Allen