Skip to content

Commit ca07b89

Browse files
Refine comments for clarity and detail in random number generation logic
1 parent 7b042b7 commit ca07b89

1 file changed

Lines changed: 20 additions & 10 deletions

File tree

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,31 @@
11
const minimum = 1; // Sets the lowest possible number that can be generated
22
const maximum = 100; // Sets the highest possible number that can be generated
33

4-
54
// In this exercise, you will need to work out what num represents?
65
// Try breaking down the expression and using documentation to explain what it means
76
// It will help to think about the order in which expressions are evaluated
87

9-
const num = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; // calculates the total number of possible values between minimum and maximum, inclusive.
10-
// Multiplying Math.random() by this total count of numbers gives a random float from 0 up to (but not including) that count.
11-
// Adding + minimum at the end shifts the whole set of numbers up so that the lowest possible value becomes minimum rather than 0.
8+
const num = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
9+
10+
/*
11+
EXPLANATION IN ORDER OF EXECUTION (OPERATOR PRECEDENCE):
12+
13+
1. (maximum - minimum + 1) — Grouping Parentheses (Highest Precedence):
14+
Calculates the total number of possible whole values between minimum and maximum, inclusive (e.g., 100 - 1 + 1 = 100 possible values).
15+
16+
2. Math.random() — Function Call:
17+
Generates a random floating-point decimal from 0 up to (but not including) 1.
18+
19+
3. Math.random() * (maximum - minimum + 1) — Multiplication:
20+
calculates the total number of possible values between minimum and maximum, (but not including) 100 (e.g., 0 to 99.999...).
21+
22+
4. Math.floor(...) — Function Call:
23+
Rounds up the decimal to the nearest whole number, giving a whole number from 0 to 99.
1224
13-
2
14-
// Math.random() returns a random decimal between 0 and 1
15-
// Math.random() * maximum(100) returns a random decimal between 0 and 99.999
16-
// Math.floor() rounds up the decimal to the nearest whole number
17-
// maximum and minimum calculates thee total output of the number(100)
25+
5. + minimum — Addition (Lowest Precedence):
26+
Shifts the whole set of numbers up so that the lowest outcome becomes `minimum` (1) instead of 0, resulting in a whole number between 1 and 100 inclusive.
27+
*/
1828

1929
// Try logging the value of num and running the program several times to build an idea of what the program is doing
2030

21-
console.log(num); // num represents a random whole number between 1 and 100
31+
console.log(num); // num represents a random whole number between 1 and 100 inclusive

0 commit comments

Comments
 (0)