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!
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 trial
Jason Nelson6,209 Points
In the random number extra credit, I'm stuck on this code:
var input= prompt(" Please type a number"); var topNumber =parseInt(input); var randomNumber = Math.floor(Math.random()*topNumber)+1;
I'm actually confused on the +1, random can give you anything between 0-1 not including 1. Math.floor rounds down what does the +1 do besides just add 1 to the floor number?
example: Math.floor(0.345)6+1 Math.floor(3.07) 3
Is this correct?
Shawn FlaniganCourses Plus Student 15,815 Points
I reformatted your question a bit to show the code properly. To try to answer your question, let's break the process down a bit.
You're right that
Math.random() will give you a number between
1, not including
1 (to be more specific, it will return a value between
When you multiply this random number by your
topNumber, you will never actually reach your
topNumber. For example, if your
10, when you multiply your two numbers, you'll reach a maximum value of
Since you're using
Math.floor() to round your results down, the maximum value you'll get from this equation is
Your minimum value will be
0 * 10, or
If you're trying to generate a number between
1 and your
1 will do the trick nicely.
Hope this makes sense!