Skip to content

Commit fc159be

Browse files
committed
Explanation of 4-random.js file
1 parent ad07e16 commit fc159be

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Sprint-1/1-key-exercises/4-random.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,47 @@ const maximum = 100;
33

44
const num = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
55

6+
console.log(num);
7+
68
// In this exercise, you will need to work out what num represents?
79
// Try breaking down the expression and using documentation to explain what it means
810
// It will help to think about the order in which expressions are evaluated
911
// Try logging the value of num and running the program several times to build an idea of what the program is doing
12+
13+
/**
14+
* Step 1: Math.random()
15+
16+
* This generates a random decimal number between 0 (inclusive) and 1 (exclusive).
17+
* Example: 0.3728, 0.9134, etc.
18+
19+
* Step 2: (maximum - minimum + 1)
20+
21+
* This calculates the range of possible numbers you want.
22+
* Here: 100 - 1 + 1 = 100
23+
* So, we’re creating a range that includes both 1 and 100.
24+
25+
* Step 3: Math.random() * (maximum - minimum + 1)
26+
27+
* This scales the random decimal to the range.
28+
* Example: If Math.random() returns 0.3728,
29+
* 0.3728 * 100 = 37.28
30+
31+
* Step 4: Math.floor(...)
32+
33+
* Math.floor() rounds down to the nearest whole number.
34+
* So 37.28 becomes 37.
35+
36+
* Step 5: + minimum
37+
38+
* Because the range started from 0, we add minimum (which is 1) to shift it to the correct range.
39+
40+
* Example: 37 + 1 = 38.
41+
42+
* So what does num represent?
43+
* num is a random integer between 1 and 100 (inclusive).
44+
* Every time you run the program, you’ll get a different number in that range.
45+
46+
* Running it several times — you’ll see numbers like 27, 99, 7, 100, etc.
47+
48+
*/
49+

0 commit comments

Comments
 (0)