C++ rand()

Started by
13 comments, last by Matt Apple 19 years, 1 month ago
this ones got me funny im learning c++ from a book and the example uses rand() to pick a number to for you t guess but the number is the same every time the program is run here is the source is the book just wrong or am i typing somthing wrong and not seeing it // Magic Number Program. #include <iostream> #include <cstdlib> using namespace std; int main() { int magic; // magic number int guess; // users guess magic = rand(); // get magic number for user to guess cout << "Enter your guess: "; cin >> guess; if(guess == magic) cout << "\n ***right***"; else cout << "You guessed the wrong number sorry \n" << magic <<"\n"; system("pause"); }
Advertisement
Didn't your parents ever tell you to seed your rands? [smile]
Try this before calling rand():

srand( (unsigned)time( NULL ) );
Put srand(time(0)); at the beginnig of your main.

srand sets the start value of rand. Without using srand you always get the default start value.
You need to initialize the random number generator with a number. If you use the current time to initialize then the random number sequence you get by calling rand() will depend on which time you run the program.

Like this:

#include<cmath>
#include<ctime> //time functions

//in your main function do this once
srand(time(0));

//then call rand and the result will depend on the time srand was called

\Jimmy H

edit: me too slow
ok thanks but now how do i get a specific range in the values?? like 1-100
rand() % 100 + 1

edit: rand() returns a random int (anything that fits in an int) so if you divide by 100 and get the rest it will be between 0 and 99 (add 1 to get 1 - 100).
thanks
does that work on any range of numbers say 1-10 or 1-15???
rand is a pseudorandom number generator (PRNG). This means that it generates a predictable sequence of numbers according to a complex formula based on the seed value. As you've been shown, you call srand to set the seed (IIRC, it defaults to 1). By saving and restoring your seeds, you can regenerate the same sequence of numbers, which can be useful in the design and implementation of, say, a replay system in your game.

To provide true randomness, however, many people seed rand with the current time, the logic being that the time at which the user will run the program, measured in milliseconds, is about as random as you can get.

Be aware that the Standard Library implementation of rand isn't the best of PRNGs. For instance, the low-order bits of the return value of rand are less random than the high-order bits, which is why using the modulo operator (%) with rand is typically discouraged. These considerations are not necessarily pertinent to your current use, but are good to keep in mind for the future.
Yes, it does.

This topic is closed to new replies.

Advertisement