Thursday, July 9, 2009

Rand() question (C++)?

Hi, I know you can use the rand() function to generate random numbers in C++ but is there a way to set it to only generate numbers within a set value? like if I wanted a variable to be a random number between 1 and 5 how would I do that?





ex. MyVariable = rand()





But how would I make it so that rand() only generates numbers between 1 and 5?

Rand() question (C++)?
number = (((double) rand() / (double) RAND_MAX) * 5 + 1);
Reply:You could just discard any number not 1-5 and pull the next rand() or in the definition of RAND_MAX change to 5
Reply:Do not use the first method, as their is no guarantee it will ever exit (it might turn into an infinite loop, but probably won't). Since rand returns a "random" integer between 0 and RAND_MAX, you can use modulus to extract a value within a given range:





int myValue = (rand() % 5) + 1;
Reply:Convert to floating point for numbers between 0 and 1 and multiply by limit. Then convert to integer:





num = (float) rand() / 32767;


No comments:

Post a Comment