New to game developing

Started by
11 comments, last by nullsquared 17 years, 9 months ago
kimi,

#include <ctime> includes the ctime library header file. This file is part of the Standard C++ Library and, among other things, lets you get what the current time is in milliseconds with the time() function.

rand() and srand() are functions in the standard c++ library that handle generating random numbers.

rand() returns a random number between 0 and 32767. Before you use rand(), you have to "seed" the random number generator (this is due to the way the computer generates random numbers).

srand() is used to seed the random number generator. This is typically done by passing in the current time in milliseconds.

So the code srand(time(NULL)); basically sets up the random number generator.

Writing num = (rand() % 100) basically means get a random number between 0 and 99. You then add one to this to get a number between 1 and 100.

% is the modulus operator. It returns the remainder of a division. The result of an expression x % y will always be between 0 and y-1, so you can use it to limit the random number generated.

Wow, thats longer than I thought it would be! Hope it helped!
Advertisement
Quote:Original post by mike223
rand() returns a random number between 0 and 32767.


I'm pretty sure that the max that rand() returns depends upon the implementation of the standard library (this means that whoever writes the compiler gets to choose and you are not guarranteed to get the same results with different compilers or different operating systems). But, that is what many compilers use.

Oh, and if you haven't used random number generators before, what 'seeding' does is it gives the generator a 'starting point'. This isn't used as the first random number, but it is used in some complex math formulas to create a psuedo random number. If it is seeded with the exact same value twice, it will produce the same results both time. Like so:

srand(5);
std::cout << rand();
std::cout << rand():

Running this program would get the same results every time that it is run. To make sure that your random number guesser doesn't always give you the same number to guess, you seed the generator with a seed that will be unique per run. The number of milliseconds that the computer has been turned on will be close enough to unique, so that is an excellent (and common) seed.
Quote:Original post by Ezbez
Quote:Original post by mike223
rand() returns a random number between 0 and 32767.


I'm pretty sure that the max that rand() returns depends upon the implementation of the standard library (this means that whoever writes the compiler gets to choose and you are not guarranteed to get the same results with different compilers or different operating systems). But, that is what many compilers use.


To extend, just to be sure, you can use RAND_MAX.

This topic is closed to new replies.

Advertisement