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 trialRussell Smitheram
2,009 PointsI can't figure out the math
This is the first challenge that's got me stuck.
I can't figure out why the function is returning numbers thar are smaller than the numbers I've given it.
For example, I passed two numbers (5, 10) to my function but on the console.log it returns 1, 2 and even minus numbers.
I'm sure I'm messing up the math part...
If anyone can help I'd truly appreciate it.
4 Answers
Michael Hulet
47,913 PointsIt looks like you're currently passing parameters into Math.random
itself, which takes no parameters. It will always return a random number between 0
and 1
and will ignore whatever parameters you pass it. As for the math, you actually look to be on the right track. The MDN documentation on Math.random
has some good sample code to show a good solution. Basically you multiply the result of Math.random()
by the result of (max - min)
, which will put the random number in a range that might be below your minimum, but close to the range that you want. After that, you add min
to it, in order to guarantee that it will never be less than that minimum. However, since you previously multiplied it by (max - min)
, it will never be greater than (or equal to) max
. Thus, it's a random number in the range you want
Katiuska Alicea de Leon
10,341 PointsWhy do the examples have to be math all the time? Ugh!
gerardo keys
14,292 Pointsfunction randNum(low, high) {
rand = Math.floor(Math.random() * (high - low + 1)) + low;
return rand;
}
document.write('<p>You\'re random number is ' + randNum(5, 10) + '</p>');
Piotr Manczak
Front End Web Development Techdegree Graduate 29,365 PointsIn my opinion it should look something like that:
function aNumber (num1, num2) { var randomNumber = Math.floor(Math.random() * (num2 - num1)) + num1; return randomNumber; }
console.log(aNumber (-500, -50));
Tyler Dix
14,230 PointsTyler Dix
14,230 PointsThis explains the math! I did a bunch of fiddling around, and didn't quite understand the math behind this.