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 trialKiran Kumar
Front End Web Development Techdegree Student 3,793 PointsI have never encountered any zero when using Math.ceil
But why does the teacher use Math.floor and extra code to get the number between 1 - 6?
Teacher's Code:
var randomNumber = Math.floor( Math.random() * 6) + 1;
He said Math.ceil might give you zero sometimes, but I never encountered zero. Math.random() always returns greater value than zero, as long as the value is not less than zero, Math.ceil returns the value of 1.
Code I tried:
var randomNumber = Math.ceil( Math.random() * 6);
Both are working exactly the same way, but I'm confused why the teacher has used Math.floor? Please help
1 Answer
Shunpan Lo
Full Stack JavaScript Techdegree Student 19,126 PointsMath.random() will return a random number between 0 (inclusive) and 1 (exclusive). Might be you are too lucky that you never meet a 0 value from Math.random(). When Math.random() gives you a 0 value:
Math.floor( Math.random() * 6) + 1 = Math.floor( 0 * 6) + 1 = 0 + 1 = 1
Thus, if you really want to value from 1 to 6. The above formula will be the only answer.
For Math.ceil( Math.random() * 6), when Math.random() gives you a 0 value:
Math.ceil( Math.random() * 6) = Math.ceil(0 * 6) = Math.ceil(0) = 0
You might have a chance getting a zero value but not 1 to 6 only.
Kiran Kumar
Front End Web Development Techdegree Student 3,793 PointsKiran Kumar
Front End Web Development Techdegree Student 3,793 PointsThat's what I was wondering xD Got it, thanks.