Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialRandolph Wang
3,614 PointsFully utilizing user's input for the RNG?
When we use the Math.random() property, I realized that since it's randomly generated decimal between 0 and 1, we probably will not be able to set the user's input as the maximum number for the RNG. Is there any logical way around this with the knowledge we have learnt so far?
My code below:
var num1 = prompt("Please enter a number: ");
var random = Math.floor(Math.random() * num1) + 1;
/* Math.floor() rounds the number down at the end
The key to thinking of the problem is Math.random() ranges from 0 to 1, so this is the initial base of the random numbers. When you multiply Math.random() by the user's input of 'num1', the product is a fractional portion of the user's input. The '+1' at the end is just in case zero happens to be randomly generated. */
document.write("Your random generated number is " + random);
Randolph Wang
3,614 PointsThanks Goce! Appreciate it!
Goce Petrov
8,302 PointsGoce Petrov
8,302 PointsI was confused also at the beginning but its simple.
The Math.floor() function returns the largest integer less than or equal to a given number
The Math.random() function returns a floating-point, pseudo-random number in the range 0–1 (inclusive of 0, but not 1)
I will try to explain to you.
Math.floor( Math.random() * ( upper - lower + 1 ) + lower );
In your case Math.floor( Math.random( P.S. RANDOM NUMBER WILL NEVER BE ONE ) * ( 100 - 99 + 1 ) + 99 );
let's do simple math. Math.floor( Math.random( 0.98653245 ) * ( 100 - 99 + 1 ) + 99
Math.floor( Math.random( 0.98653245 ) * ( 2 ) + 99 ) so you do bracket first so 100 - 99 + 1 = 2 next step
Math.floor( Math.random( 0.98653245 ) * 2 + 99) so now multiplication 0.98653245 (this is math random) * 2 = 1.9730649
Math.floor( 1.9730649 + 99 ); is 100.9730649
This is the post that I explained to one of the students how Math.floor and Math.random work.
Hope this is helpful.