PDA

Click to See Complete Forum and Search --> : C++ Help


jaguar291
September 30th, 2002, 03:50 AM
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

Lucas420
September 30th, 2002, 04:28 AM
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

dspeidel
September 30th, 2002, 05:30 AM
Originally posted here (http://www.AntiOnline.com/showthread.php?threadid=#post) 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

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.html#SECTION002100000000000000000 for details on the time function.

Cheers,

-D

ammo
September 30th, 2002, 05:55 AM
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

shantz
September 30th, 2002, 04:12 PM
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