|
-
October 16th, 2002, 06:30 PM
#1
quick question
ok guys, im new to the C++ language (i know a little about VB) and im in class where we have to write some basic programs. my only question (so far) is what is the basic code for having the computer generate a random number between 1 and 100 (including both)? i havent been able to find anything in my text. thanks in advance.
-
October 16th, 2002, 06:52 PM
#2
well, in the math library...
There are the functions srand(int) and rand(). These are best for beginners to use. Something like (in main.cpp)
Code:
// up at top
#include <math.h>
// down in function
// seed the random number generator
srand(YOURSEEDHERE);
// then to get your random number
myrandvariable = (rand() % 100) + 1;
This is not a cryptographically secure random number generator but it works. Usually is best to seed the random number with a time value. If you are asking how to write your own random number generator, that is different and will explode this thread into a heated debate on definitions of "cryptographically secure" and "statistically random".
-
October 16th, 2002, 08:37 PM
#3
What I usually do is include
#include <time.h>
and then I can do
srand(time(NULL));
to make the numbers random. What rand() does is return a very large integer. Using the modulus (%) gives the remainder so you can turn the number rand() gives you into a meaningful number. In galathaea's example, rand()%100 gives a number from 0-99 (a number, when divided by 100, has a remainder from 0-99), and rand()%100+1 gives a number from 1-100, the desired range. Since you know what the rand() function does now, you can know how to use it correctly.
SolarFlare
Those who cling to life die and those who defy death live. -Sun Tzu
cout << endl;
return 0;
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|