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 trialDea Kristina
Courses Plus Student 1,792 Pointswhy +1?
Why do we have to add '+1' for the : Math.floor(Math.random() * xxx) + 1 ? Is it because we assume that it's a dice that has 1-6 values? If we don't assume a dice, can we just skip the +1 then? Thanks! :)
2 Answers
Steven Ang
41,751 PointsThe Math.floor will remove all the decimal places. Inside the Math.floor function, we use the Math.random to generate random numbers and multiplied it by 6 since it's a die. Remember that just solely using Math.random alone, we will always get numbers below 0 but not 1? That's why we plus it by 1 if we don't you will get numbers between 0 and 5.
Ruby Bassi
3,873 PointsI'm wondering the same thing: Is the +1 only relevant if using the die scenario?
jaspergradussen
5,876 Points+1 in Math.floor(Math.random() * xxx) + 1 is to be able to include the original input (being xxx). Say it where 10. I could never be randomly 10 because without +1 it would be a number between 0 and 9.
Because, Math.random() is a number between 0 and <1 and multiply that by 10, you never will be able to get the 10 (0.999999999 * 10 =NOT 10). Include Math.floor() and it makes sure that 9.99999 goes down to 9. So to make it reach 10 in the equation you add a +1.
Ruby Bassi
3,873 Pointsthat makes total sense. Thanks Jasper Gradussen!
Dea Kristina
Courses Plus Student 1,792 PointsDea Kristina
Courses Plus Student 1,792 PointsThanks! yeah I understand that, but this means that the +1 is because it assumes a dice with 6 values right :)