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 trialJohn Bamberg
9,774 PointsIf 1 is added to the end? How to I return 1?
Math.floor( Math.random() * 6 ) + 1
If 1 is added to the end of the statement. How will I ever return 1?
2 Answers
Ted Sumner
Courses Plus Student 17,967 PointsRandom numbers return a value between 0 and 1. The floor function rounds down. Without the 1, you get values between 0 and 5, thus you need a +1 to get between 1 and 6.
Iain Simmons
Treehouse Moderator 32,305 PointsOr another way to look at it, if Math.random()
returns anything less than 1/6 (0.1666666666... etc), that will be multiplied by 6 and still be equal to a value less than 1. That will be 'floored' to 0, so you add the 1 to it to get 1.
Not sure if that makes any more sense than the way it was already explained...
You could always store the random number in a variable and then perform the operations on it one-by-one and print out the result at each step if you'd like to see how it all works.
Ted Sumner
Courses Plus Student 17,967 PointsTed Sumner
Courses Plus Student 17,967 PointsThe Math.floor() function returns the largest integer less than or equal to a given number.