11const minimum = 1 ;
22const maximum = 100 ;
33
4- // const num = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
5- // console.log(num);
4+ const num = Math . floor ( Math . random ( ) * ( maximum - minimum + 1 ) ) + minimum ;
5+ console . log ( num ) ;
66
77
88// In this exercise, you will need to work out what num represents?
99// Try breaking down the expression and using documentation to explain what it means
1010// It will help to think about the order in which expressions are evaluated
11- // Try logging the value of num and running the program several times to build an idea of what the program is doing
11+ // Try logging the value of num and running the program several times to build an idea of
12+ // what the program is doing
1213
13- / * M a t h .f l o o r ( ) t a k e s t h e i n t e g e r N u m b e r
14- Math . random ( ) will take a number between 0 ( inclusive ) and 1 ( no inclusive ) eg . ( 0.345 , 0 , 123 )
15- Math . random ( ) * ( maximum - minimum + 1 ) : this multiply the random decimal number
14+ /*
15+ Math.floor() Math.floor() rounds down the decimal result from the previous step to the
16+ nearest integer. This step ensures the random number is a whole number.
17+ have a random integer between 0 and 99, inclusive.
1618
19+ Math.random() will take a number between 0 (inclusive) and 1 (no inclusive) eg. this
20+ will be decimal numbers (0.345, 0,123)
21+
22+ Math.random() * (maximum - minimum + 1): is multiplied by 100, creating a new range.
23+ Now, Math.random() * 100 generates a random decimal number between 0 and 100
24+ (not including 100). Example 0.0, 25.4, 99.99, etc.
1725
26+ (maximum - minimum + 1) This part calculates the range of numbers you want to include,
27+ which is from 1 to 100. Subtracting minimum from maximum gives 99, and adding 1 results
28+ in 100. So, this range means we’re looking to generate a random number between 0 and 99
29+ and then shift it to between 1 and 100.
1830
31+ + minimum:
32+ Adding minimum (which is 1 in this case) shifts the entire range up by 1.
33+ Now, instead of getting a range of 0–99, the range becomes 1–100.
34+ so, num will now be a random integer between 1 and 100.
1935
36+ */
2037
21- // in this example taken from mdn we see the same function being called and will generate a random number between the minimun and maximun
38+ // in this example taken from mdn we see the same function being called and will generate a
39+ //random number between the minimum and maximum
2240
2341function getRandomArbitrary ( min , max ) {
24- return Math . random ( ) * ( max - min ) + min ;
42+ return Math . floor ( Math . random ( ) * ( max - min ) + min ) ;
2543 }
2644
2745console . log ( getRandomArbitrary ( minimum , maximum ) ) ;
0 commit comments