@@ -7,3 +7,45 @@ const num = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
77// Try breaking down the expression and using documentation to explain what it means
88// It will help to think about the order in which expressions are evaluated
99// Try logging the value of num and running the program several times to build an idea of what the program is doing
10+
11+
12+ console . log ( num )
13+
14+ // num returns a value of 60, running it again returns a value of 15, looking at the code I see a .random() function
15+ // I can make a hypothesis that this returns a random number of some kind, hence the inconsistent result
16+
17+ // Let's find out...
18+ // Code in inner-most brackets is evaluated first
19+ // I would expect (maximum - minimum + 1) to be evaluated first (100 - 1 + 1) would equal 100
20+
21+ console . log ( maximum - minimum + 1 )
22+
23+ // the result was 100
24+ // this part of the code is then multiplied by Math.random()
25+
26+ console . log ( Math . random ( ) )
27+
28+ // running this code many times, it appears Math.random() returns a random number between 0 and 1
29+ // checking documentation online, this is correct (actually between 0 and 0.99999999999)
30+ // therefore Math.random() * (maximum - minimum + 1) should return a random number between 1 and 100
31+
32+ console . log ( Math . random ( ) * ( maximum - minimum + 1 ) )
33+
34+ // It does, it returns it with many decimal places, the result of num didn't have any decimal places
35+ // The next part of the code that is run is Math.floor, let's see what this does
36+
37+ const number = Math . random ( ) * ( maximum - minimum + 1 )
38+ console . log ( number )
39+ console . log ( Math . floor ( number ) )
40+
41+ // because Math.random() creates a new random number every time it is run, I had to set the
42+ // result to a variable so I can use the same number in multiple functions
43+ // When number is 87.52, Math.floor is 87, when number is 70.02, math.floor is 70
44+ // The function Math.floor appears to be rounding down
45+ // Checking the documentation, this is true, it returns the largest integer <= the given number
46+
47+ // Therefore Math.floor(Math.random() * (maximum - minimum + 1)) must give random numbers between 0 and 99
48+ // The final part is the addition of minimum (+1)
49+
50+ // Therefore I can see this code produces a random whole integer between minimum and maximum
51+ // Which in this case is an integer between 1 and 100
0 commit comments