22 lines
1.4 KiB
Markdown
22 lines
1.4 KiB
Markdown
|
We now move away from normal math calculations and move to the topic of random numbers.
|
||
|
Your task will be, to code a program, that rolls a dice and prints out the number.
|
||
|
|
||
|
## Knowledge
|
||
|
|
||
|
For that we need to include new functionality. To do that, we need to write: ``#include <stdlib.h>;``.
|
||
|
In there are among other instructions **srand** and **rand**.
|
||
|
To call these instructions you have to put open and closed parentheses behind them.
|
||
|
|
||
|
Because computers cannot create real random numbers but instead fake randomness with complex functions, we need to set a starting point for our **random number generator**, a so called seed that changes every time we call the program.
|
||
|
To do that we use the ``srand()`` instruction, which sets the seed of the random number generator. The only problem is, every time we run the program we would end up with the same result.
|
||
|
To avoid this we will also include the instruction time with ``#include <time.h>`` to get the current time and pass that as the seed.
|
||
|
|
||
|
We then can use ``rand()`` to get a random number. Because we only want numbers between 1 and 6, we have to use the modulo-operator %.
|
||
|
Don't worry, if you are not familiar with the math-concept of modulo. It just gives you the remainder of a whole number division.
|
||
|
So any number modulo 25 will give you a number between 0 and 24.
|
||
|
|
||
|
## Task
|
||
|
|
||
|
So that is all you need to know about random numbers. Now try to implement the dice program.
|
||
|
|