I agree with the two previous posts: use the rand() function but here's a little more info.
If you use rand() and don't seed the random number generator, your next run of your program will generate the SAME random numbers again. To fix this, use this once in your program:
srand( %26lt;some_random_value%26gt; ).
Also, if you want to determine the range of the numbers you want, then you should use the modulus operator (%). If you want the random number to be in the range of 0 to 9, then use rand()%10, if want a range of 2 to 7 use rand()%6+2.
Ex:
#include %26lt;ctime%26gt; // For time()
#include %26lt;cstdlib%26gt; // For srand() and rand()
. . .
srand(time(NULL)); // Initialize random number generator with current time as seed.
. . .
r = (rand() % 5) + 11; random number in range of 11 to 15
How do I creat an integer in C++ that is a random number. Do i type int num1; //random number?
you have to call a function called rand() it is in the math header files and modify the result to get it as far as i can tell.The math function that returns the remainder of a division works well to get the desired result. have fun.
Reply:Use then rand() function
garden centre
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment