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 trialEuan Burton
3,037 PointsUsing math.random and Math.floor or Math.ceil for 6-sided die roll behaviour.
First I am really liking Dave's videos. In this last one we were making a program to display a six-sided dieroll.
I have one question with regard to the logic about using;
" var dieRoll = Math.floor( Math.random() * 6) +1; "
vs
"var dieRoll = Math.ceil( Math.random() * 6) ; "
As explained by Dave, there is a small chance that the math.random would return a 0, and math.ceil of 0 is 0, therefore the die roll could sometimes return a zero result.
But isn't the same logic true for the floor method sometimes returning a 1, and therefore this code could potentially execute to 7?
Cheers,
Euan
1 Answer
Shawn Flanigan
Courses Plus Student 15,815 PointsEuan,
Good question, but Math.random()
will never return 1. The closest it can get is something like 0.9999999999999999.
Euan Burton
3,037 PointsEuan Burton
3,037 Pointsok great!
Im not a math expert, but i'm guessing that the reason for that is that the having it return a value of 0-1, including both 0 and 1, would be infinitesimally greater than the width of one full integer. Makes sense. thanks a lot!