Archived

This topic is now archived and is closed to further replies.

DM7

random numbers?

Recommended Posts

rand() ????

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]

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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.


  
#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]

Share this post


Link to post
Share on other sites