random numbers?
How do I generate random numbers in c++?
I also need to know how to have a number vary slightly like hp damage in an RPG
rand() ????
if you want the random number within a certaion range 0 to ?
then write a function such as :
if you want the numbers to be within a specified low and high range write a function like :
for floats this would be :
hth
necr0
[edited by - necr0 on July 30, 2002 4:07:30 AM]
if you want the random number within a certaion range 0 to ?
then write a function such as :
int Random(int range){ if (range == -1) // check for divide-by-zero case { return((rand() % 2) - 1); } return(rand() % (range + 1));}
if you want the numbers to be within a specified low and high range write a function like :
int Random(int lo, int hi){ if ((hi - lo + 1) == 0) // check for divide-by-zero case { if (rand() & 1) return(lo); else return(hi); } return((rand() % (hi - lo + 1)) + lo);}
for floats this would be :
float Random(float min, float max){ float randNum = (float)rand() / RAND_MAX; float num = min + (max - min) * randNum; return num;}
hth
necr0
[edited by - necr0 on July 30, 2002 4:07:30 AM]
hey thanks
are there any header files that I should include to use rand()?
I get an error that rand has an undeclared identifier. Normally I''d know how to fix this but I don''t know what I would put in a rand() function
I''m kinda new to this.. over only covered up to references in c++. So if I say something dumb I hope you''ll forgive me
are there any header files that I should include to use rand()?
I get an error that rand has an undeclared identifier. Normally I''d know how to fix this but I don''t know what I would put in a rand() function
I''m kinda new to this.. over only covered up to references in c++. So if I say something dumb I hope you''ll forgive me
Under linux, rand() is in stdlib.h. I would assume that it is the same under Windows.
-------
Andrew
[edited by - acraig on July 30, 2002 2:05:23 PM]
-------
Andrew
[edited by - acraig on July 30, 2002 2:05:23 PM]
And don't forget to call srand() once at the beginning of your program, otherwise you'll generate the same random numbers every time you run your program.
[edited by - cgoat on July 30, 2002 2:53:10 PM]
#include <iostream>#include <cstdio>#include <cstdlib>#include <ctime>using namespace std;int main(){ srand(time(NULL)); int i; for(i=0; i<1000; ++i) { int r = rand() % 16; cout << "Random Value: " << r << endl; } return 0;}
[edited by - cgoat on July 30, 2002 2:53:10 PM]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement