I need a little help, can someone teach me how to generate
a random number and store it as a variable in C++. Thanks.
Jaguar291
Printable View
I need a little help, can someone teach me how to generate
a random number and store it as a variable in C++. Thanks.
Jaguar291
The random number generator in the STD lib is a little tricky. Just put this function is the code somewhere :
typedef unsigned int UINT;
UINT Random(UINT n, UINT seed) {
srand(seed);
UINT num = rand();
UINT ret = (n * num) / RAND_MAX;
return ret;
}
----That should do it,
Parameter "UINT n" :
lets say you want a random number between 1 and 10 ; well then "n" would equal 10.
Parameter "UINT seed" :
just set this to any number really, it just get the generator going.
SANDMAN
If I recall the seed parameter is optional but if you don't use it the random number is always the same. That will happen if you do seed it unless you use a changing value such as the time the program is being run. See http://www.cs.cf.ac.uk/Dave/C/node21...00000000000000 for details on the time function.Quote:
Originally posted here by Lucas420
Parameter "UINT n" :
lets say you want a random number between 1 and 10 ; well then "n" would equal 10.
Parameter "UINT seed" :
just set this to any number really, it just get the generator going.
SANDMAN
Cheers,
-D
The code is ok, but just two little precisions:
1- You don't have to define the typ UINT... declaring the variables as unsinged int directly works just fine (in fact I believe rand() returns an signed int (although it returns values between 0 and RAND_MAX)
2- Also, for the seed, most of the time, the time is used:
// Needs time.h
#include <time.h>
//...
srand( (unsigned)time( NULL ) );
Ammo
For a simple and somewhat comprehensive information on random numbers, read my tutorial on random nos which i posted here a couple of weeks back. it was titled. " Random Numbers Randomized".
If u need any further clarification, feel free to post