|
1 | 1 | const minimum = 1; |
2 | 2 | const maximum = 100; |
3 | 3 |
|
4 | | -const num = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; |
| 4 | +const num = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; // num generates a random whole number between minimum and maximum |
5 | 5 |
|
6 | 6 | // In this exercise, you will need to work out what num represents? |
7 | 7 | // Try breaking down the expression and using documentation to explain what it means |
8 | 8 | // It will help to think about the order in which expressions are evaluated |
9 | 9 | // Try logging the value of num and running the program several times to build an idea of what the program is doing |
| 10 | + |
| 11 | +// Below I will be breaking down the expression: const num = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; |
| 12 | + |
| 13 | +// First you will need to generate a random decimal number between 0 and 1 |
| 14 | +const decimal = Math.random(); |
| 15 | + |
| 16 | +// Then calculate the range size |
| 17 | +const range = maximum - minimum + 1; |
| 18 | + |
| 19 | +// Then scale the decimal to the range |
| 20 | +const scaled = decimal * range; |
| 21 | + |
| 22 | +// Then round down to get a whole number |
| 23 | +const floored = Math.floor(scaled); |
| 24 | + |
| 25 | +// Then shift the number up to start at the minimum |
| 26 | +const result = floored + minimum; |
| 27 | + |
| 28 | +// You can log each part to understand the process |
| 29 | +console.log("decimal:", decimal); |
| 30 | +console.log("range:", range); |
| 31 | +console.log("scaled:", scaled); |
| 32 | +console.log("floored:", floored); |
| 33 | +console.log("result:", result); |
0 commit comments