@@ -3,7 +3,37 @@ const maximum = 100;
33
44const num = Math . floor ( Math . random ( ) * ( maximum - minimum + 1 ) ) + minimum ;
55
6- // In this exercise, you will need to work out what num represents?
7- // Try breaking down the expression and using documentation to explain what it means
8- // It will help to think about the order in which expressions are evaluated
9- // Try logging the value of num and running the program several times to build an idea of what the program is doing
6+ // Breakdown of the 'num' declaration
7+ // The expression of `num` can be broken down into several discrete steps:
8+
9+ // 1. `Math.random()`, this generates a random floating point number
10+ // This number is between 0 (inclusive) and 1 (exclusive)
11+ console . log ( "Math.random():" , Math . random ( ) ) ;
12+
13+ // 2. `(maximum - minimum + 1)` this part simple resolve to 100
14+ console . log ( "maximum - minimum + 1:" , maximum - minimum + 1 ) ;
15+
16+ // 3. By multiplying steps 1 and 2, the floating point number is scaled from 0-1 to 0-100
17+ // This adjusted scale is defined by the `minimum` and `maximum` variables declared earlier
18+ console . log (
19+ "Math.random() * (maximum - minimum + 1):" ,
20+ Math . random ( ) * ( maximum - minimum + 1 )
21+ ) ;
22+
23+ // 4. `Math.floor()` then rounds down to the nearest whole number
24+ // Turning the floating point number into a whole number and adjusting the range from 0-99
25+ console . log (
26+ "Math.floor(Math.random() * (maximum - minimum + 1)):" ,
27+ Math . floor ( Math . random ( ) * ( maximum - minimum + 1 ) )
28+ ) ;
29+
30+ // 5. Lastly, `+ minimum` shifts the result up by the value of 1
31+ // In effect, this adjusts the range from 0-99 to 1-100
32+ console . log (
33+ "Math.floor(Math.random() * (maximum - minimum + 1)) + minimum:" ,
34+ Math . floor ( Math . random ( ) * ( maximum - minimum + 1 ) ) + minimum
35+ ) ;
36+
37+ // The final result is a random whole number between minimum (1) and maximum (100)
38+ // Where 100 is an inclusive valid value in the range
39+ console . log ( "num:" , num ) ;
0 commit comments