Please I really need help on this. I'm new to C++ and i'm doing a college assignment. I did some searching over google and found these 2 ways I can do it.
((rand() % 11 - 2) + 2 + 1)
((rand() % 11 + 2))
My goal is to get a random number between 2 and 11..... But everytime I compile the program the "random" number is always 9!! How can I get this to work?
Need to know how to use random numbers in C++?
Random numbers in this function are generated using what is known as a 'seed' - if you don't have any code to change the value of the seed, it will always be the same, generating the same number sequence. An example of the code you would need can be found here: http://www.cplusplus.com/reference/clibr...
Reply:Try using this bit of code.
int main()
{
int r;
randomize(); // Setup the random number generator.
// It is responsible for making the result of rand() being more
// random. If you not call this function, you get the same output from rand().
r = (rand() % 10 + 2); // Get random value from 2 to 11.
printf("r = %d\n", r);
}
Make sure you call randomize() only once in your program otherwise you might end up with the same sequence of random numbers.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment