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 trial
Haoz Bach Ly
3,709 PointsReally need some feedback!
According to the random challenge, it requires the user to create a range between [a;b] with b>a and both of them are random visitor's inputed integers. So my question contains three parts:
- Is my below mathematical explanation for the question correct?
[a;b] = [0 + a; b -a +a] Math.random() -> [0;1) Math.random() * (b-a) -> [0;b-a) If I use the floor function and the result is this: Math.floor(Math.random() * (b-a)) -> [0; b-a-1] Wrong way to create (b - a) gap. If I use the ceil function and the result is this: Math.ceil(Math.random() * (b-a)) -> [0; b-a] Math.ceil(Math.random() * (b-a)) + a -> [a;b]
- Secondly, do you see anything wrong in my script written below?
var firstNumber = prompt("Please give me a number."); var secondNumber = prompt("Give me another number that\'s smaller than the first one."); var numberx = Math.ceil(Math.random() * (parseInt(firstNumber) - parseInt(secondNumber))) + parseInt(secondNumber); document.write(numberx);
- Finally, is there any function that is able to compare the margin between two inputed numbers regardless the order - either the smaller is first or second - of the visitor log in the prompt command? As you can see, my script would go wrong if the user enters the first value which is smaller than the second.
Any help is really appreciate about this matter.
1 Answer
Steven Parker
243,656 Points- The formula should use "floor" instead of "ceil" to get the right range.
- Once corrected as discussed in point 1, the script otherwise appears correct.
- You can apply the "abs" function on the number difference ("
Math.abs(a - b)") to guarantee a positive range.