|
1 | | -const minimum = 1; |
2 | | -const maximum = 100; |
| 1 | +// MIN and MAX are constants that define the lower and upper bounds for our random number range. |
| 2 | +const MIN = 1; |
| 3 | +const MAX = 10; |
3 | 4 |
|
4 | | -const num = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; |
5 | | - |
6 | | -// In this exercise, you will need to work out what num represents? |
7 | | - |
8 | | -//After running this exercise a few times I can see that 'num' is a random number between 1 and 100 |
| 5 | +// Math.random() returns a decimal value in the interval [0, 1) |
| 6 | +// Multiplying by (MAX - MIN + 1) scales the interval to [0, MAX - MIN + 1) |
| 7 | +// Applying Math.floor() converts the value to an integer within [s0, MAX - MIN] |
| 8 | +// Finally, adding MIN shifts the interval to [MIN, MAX], which is our desired result. |
9 | 9 |
|
| 10 | +const num = MIN + Math.floor(Math.random() * (MAX - MIN + 1)); |
10 | 11 | console.log(num); |
11 | | - |
12 | | -// Try breaking down the expression and using documentation to explain what it means |
13 | | - |
14 | | -// at the top we can see our minimum and maximum values which are fixed therefore Constants, |
15 | | -// we then have our variable num which is assigned a value using the Math object and its methods floor and random |
16 | | -// Math.random() generates a random decimal number between 0 (inclusive) and 1 (exclusive) |
17 | | -// We then multiply this random number by the range of our desired numbers which is (maximum - minimum + 1) |
18 | | - |
19 | | -// It will help to think about the order in which expressions are evaluated |
20 | | - |
21 | | -//the same as math, multiplication is done before addition and subtraction |
22 | | -// so we first calculate (maximum - minimum + 1) which is (100 - 1 + 1) = 100 |
23 | | -// then we multiply the random decimal number by 100 which gives us a number between 0 and 100 (but not including 100) |
24 | | -// then we apply Math.floor() to round down to the nearest whole number, giving us a number between 0 and 99 |
25 | | -// finally we add the minimum value (1) to shift the range up, resulting in a final value between 1 and 100 (inclusive) |
26 | | - |
27 | | -// So in summary, 'num' is a random integer between 1 and 100, inclusive of both endpoints. |
28 | | - |
29 | | - |
30 | | -// Try logging the value of num and running the program several times to build an idea of what the program is doing |
31 | | - |
32 | | -//you can see how random function generates different numbers each time the program is run |
33 | | -//and how the range is always between 1 and 100 |
34 | | - |
0 commit comments