Presentation is loading. Please wait.

Presentation is loading. Please wait.

MR. CRONE Generating Random Numbers. Random Numbers Many programs require the computer to generate random numbers Random numbers are used in many applications.

Similar presentations


Presentation on theme: "MR. CRONE Generating Random Numbers. Random Numbers Many programs require the computer to generate random numbers Random numbers are used in many applications."— Presentation transcript:

1 MR. CRONE Generating Random Numbers

2 Random Numbers Many programs require the computer to generate random numbers Random numbers are used in many applications  Computer Games  Statistical Analysis  Probability

3 Random Numbers In order to create a random number, C++ compilers provide us with the rand() function The rand() function returns a random integer that can then be assigned to a variable Example) int main(){ int myRandom = rand(); return 0; }

4 Random Numbers The rand() function is contained within the header file The header file must be included in order to use the rand() function #include using namespace std; int main(){ int myRandom = rand(); return 0; }

5 Random Numbers The code below is intended to provide us with 5 random numbers **Assume all proper header files are included int myRand; for(int i = 0; i < 5; i ++){ myRand = rand(); cout << myRand << endl; }

6 Random Numbers Unfortunately, the code below will continue to produce the same set of random numbers time after time To obtain new random numbers every time the program is compiled, we must use a technique called seeding int myRand; for(int i = 0; i < 5; i ++){ myRand = rand(); cout << myRand << endl; }

7 Random Numbers Seeding allows the program to produce a completely different set of random numbers every time the program is compiled The seeding function is srand() and this function is contained within the header file In order to properly use srand(), we must pass the following argument: time(NULL) time(NULL) is a function contained within the header file The time(NULL) function reads the computer’s internal clock time in seconds and uses this information to initialize random numbers

8 Random Numbers Proper use of the seeding technique is shown below The code below will now produce a new sequence of random numbers each time the source code is compiled srand(time(NULL)); int myRand; for(int i = 0; i < 5; i ++){ myRand = rand(); cout << myRand << endl; }

9 Random Numbers The rand() function produces a random number in the following interval: 0 <=rand() <= RAND_MAX RAND_MAX is a constant and is defined in the header file RAND_MAX = 32,767

10 RAND_MAX The RAND_MAX constant can be used within your own program To print RAND_MAX refer to the code below: cout << RAND_MAX << endl;


Download ppt "MR. CRONE Generating Random Numbers. Random Numbers Many programs require the computer to generate random numbers Random numbers are used in many applications."

Similar presentations


Ads by Google