Generating Random Numbers
Video Summary: https://youtu.be/AT0P3FGt7qg
Sometimes, you will want to have random input for your program, such as if you were creating a game of luck or making sure your program won't crash with unexpected values. You can do this with the built in functionality and libraries for C++.
You can generate a "random" number simply by assigning a variable the value rand():
However, there are two problems with this. First, the number will not be in any defined range and might not be useful to you. You may want to use the modulus operator '%' and use the remainder of some division. For example, if you wanted a number between 0 and 5, you would use % 6 (max value you want + 1):
The second problem is that your number will not actually be random. Computers run on algorithms, which means they have a process of generating this number that will always result in the same output. If you don't want the same numbers every time, you could consider using a seed to modify the outputs using srand(seed_number).
But changing your seed every time you run the program is not ideal. To generate numbers you or a user would not be able to predict, you would want the seed to be something that is constantly changing. You could achieve this by using the time library, and using the computer's clock to generate the numbers. Since time is always changing, you will get different numbers each time you hit run, which provides essentially random numbers.
- include <time.h> at the top of your program
- use time(NULL) as your seed_number in srand
Exercise
Create a dice game that generates two random numbers, one for each player. You will need to use modulus and addition to make sure the numbers are between 1 and 6. Use a time seed so that the results vary every time you run the program. A sample output could look like this:
Player two rolled a 2