Topic : Using rand() and srand()
Author : Alex Gartrell
Page : 1

NOTE: I am still a newbie myself so this code may be incorrect. If you spot any problems, please contact me at mad_scientist89@hotmail.com

Header Files

To get random numbers it is important that you include the following header files

time.h
stdlib.h
iostream.h


You include them by adding this to the top of your source

#include <iostream.h>
#include <stdlib.h>
#include <time.h>


You can include them in any order, so long as it comes before anything else.

srand()

Before you can use the rand() function you have to call srand(). srand basically just states the starting off point for rand. A way of seeding rand is by typing simply the following.

srand(0);

However, this will give you the same numbers every time the program is started.

In order to make it as random as possible I reccomand calling the time() function. It looks like this when you use srand() and time() together.

srand(time(0));

rand()


To get the actual random number you have to call rand(). An easy way to do this is to use the following code.

int n; //n can be anything.
n=rand();


you can then use n as anything you wish.

Reducing the value that n can have (setting a maximum)

The maximum number of rand() by itself is 32767. That is irrelevent as long as you remember that it is permanantly stored in the constant RAND_MAX.

To set a max, you have to find out what the difference in between your largest and smallest numbers are. Then you have to divide RAND_MAX by the difference. You then take the result of your division problem and divide the result of the rand() function by the same. You can see it done below.

int max; //maximum number you want to see
int min; //lowest number you want to see
int range; //difference between max and min
int x;
int n;
int to_be_displayed;

range = max - min;

x = rand();


n = rand_max; //Compilers will not allow you to use a set constant in a math problem

to_be_displayed = (x / (n / max)) + min;

Putting it all together

The following example code uses all of the concepts discussed in this tutorial.

#include <iostream.h>
#include <stdlib.h>
#include <time.h>

int main()
{
int max, min, range, a, rmax, to_be_displayed;

srand(time(0));

cout<<"Enter a maximum number";
cin>>max;
cout<<"Enter a minimum number";
cin>>min;

range = max - min;

rmax = RAND_MAX;

a = rand();

to_be_displayed = (a / (rmax / range)) + min;

cout<<"Your random number is : "<<to_be_displayed;

return 0;
}



Page : 1