Jump to content
  • Advertisement
Sign in to follow this  
BloodLust666

Random Function

This topic is 4635 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

Advertisement
Quote:
Also, how should i make my own random function that takes in a Min, and Max and returns a value between the two?

int randomNumber = (rand() % (max-min)) + min;

Share this post


Link to post
Share on other sites
doesn't rand() return a value between 0 and 1? (if not using srand(long) to define that max)

Here's what i came up with, is thie correct?

long GenerateRandom(long Min, long Max)
{
long Num;
srand(Max - Min);

Num = rand() + Min;
return Num;
}

Share this post


Link to post
Share on other sites
srand sets the seed for the random number generator. The seed should be from a constantly changing source. A milli or microsecond counter would work. As stated in the manpage, rand returns an integer between 0 and RAND_MAX as defined in stdlib.h. Read the linked manpage for details.

Sidenote: Variable names begin with lowercase letters by convention.

Share this post


Link to post
Share on other sites
step-by-step how to do it:

float RN = rand();
float result1 = RN / RAND_MAX;
float low = 2, high = 5;
float result1 = result1 * (high - low) + low;
cout << "result: " << result2 << endl;


one line way to do it(assuming high and low are defined floats:

float result = (rand()*1.0 / RAND_MAX) * (high - low) + low;


It is VERY important that rand() be converted into a floating point number in C++. If you have an integer divided by another integer it rounds so if you have, say rand() equals 10 then 10 / RAND_MAX will be zero. If you convert it to a float before hand then it will do floating point math and you won't lose any precision. The code is fairly straight forward, I hope.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

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

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!