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 trialAlexis Donnard
4,931 PointsSolving with "if" statement
Hi guys,
I solved the problem using an "if" statement, depending on if the first argument is higher than the second. Just wanted to know if this is correct:
function getRandom(a,b){
if (a<b){
return Math.floor(Math.random()*(b-a+1))+a;
} else {
return Math.floor(Math.random()*(a-b+1))+b;
}
}
Thanks for the answer and sorry for my bad english (I'm French :) )!
2 Answers
Daniel Newman
Courses Plus Student 10,715 Pointsfunction getRandom(a, b) {
if (a < b) {
return Math.floor(Math.random()(b - a + 1)) + a;
} else {
return Math.floor(Math.random()(a - b + 1)) + b;
}
}
You forgot to multiply "*" your expression of random number and the next expression. Or you have not put (b-a+1) and (a-b+1) inside random() method. What will happen if I put 0 and 0 inside getRandom()?
Iain Simmons
Treehouse Moderator 32,305 PointsYou can't put anything inside the random()
method, or in other words, it doesn't accept any arguments.
And if you pass 0 and 0 to getRandom()
, you will get 0, which is correct (it's the only possible answer).
Alexis Donnard
4,931 PointsHey thanks for the quick answer! Actually I did used the * sign but it did not print when I copied and pasted my code from gedit... Weird. I ran my code an it works so I think its ok :) Once again, thanks for your answer.
Iain Simmons
Treehouse Moderator 32,305 PointsIain Simmons
Treehouse Moderator 32,305 PointsAdded code to a code block, now you can see your
*
.