Jump to content
  • Advertisement

Archived

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

DM7

random numbers?

This topic is 5927 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


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

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

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!