Click to See Complete Forum and Search --> : quick question
Kibbles an Bits
October 16th, 2002, 06:30 PM
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.
galathaea
October 16th, 2002, 06:52 PM
There are the functions srand(int) and rand(). These are best for beginners to use. Something like (in main.cpp)
// 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".
SolarFlare
October 16th, 2002, 08:37 PM
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.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.