Page 1 of 1

Random Variables?

PostPosted: Wed Nov 30, 2011 3:04 am
by Wertyboy
How? for example: sometimes is "var=1;" sometimes is "var=2;"
Is it possible?

Re: Random Variables?

PostPosted: Wed Nov 30, 2011 3:36 am
by SuperSonic
Use the rand(int) function. Like this:
Code: Select all
int var = rand(5);//This will make var equal a random number that can be as low as 0 and as high as 4

And if you want to make a function that let's you choose the minimum and maximum values, you can do this:
Code: Select all
float GetRandomNumber(int MIN, int MAX)
{
    return rand(MAX - MIN) + MIN + 1;//This will return a random number that is in between MIN and MAX
}

And here is how you can use the function:
Code: Select all
int var = GetRandomNumber(3, 5);//This will set var to equal a random number in between 3 and 5

If you need me to explain anything, just ask :D

Hope that was helpful :P

Re: Random Variables?

PostPosted: Thu Dec 01, 2011 8:11 am
by foleyjo
Forgive my ignorance but why do you plus 1 at the end of the random function?
Does that not make it so the min value will never be selected?

eg:
min 5 max 10

10 - 5 = 5
rand(5) = 0 selected

0+ 5= 5

5+ 1 = 6

return 6

Re: Random Variables?

PostPosted: Thu Dec 01, 2011 2:27 pm
by Game A Gogo
Code: Select all
float GetRandomNumber(int MIN, int MAX)
{
    return rand(MAX - MIN + 1) + MIN;//This will return a random number that is in between MIN and MAX
}


this is probably better then

Re: Random Variables?

PostPosted: Fri Dec 02, 2011 3:31 am
by SuperSonic
foleyjo wrote:Forgive my ignorance but why do you plus 1 at the end of the random function?

I think (I'm not sure but I think) that the rand function returns a value that can be equal to or greater that 0 and less than the max number so you have to add that +1. But actually, my code is wrong and Gogo's is right. I just found that out :D

@Werty: Forgive me for misleading you haha :lol: