Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Display random temp and 3 day forecast Reply To: Display random temp and 3 day forecast

#169889
dyr
Participant

Math.random always gives a number between 0 (inclusive) and 1 (exclusive) and has nothing to do with the range in your for loop.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

You just scale it to whatever range you want. So if you want the high’s to be between 10 and 20 you would multiply by 10 and add 10. Math.random() * 10 + 10. Multiplying the random number by 10 will give you numbers in a range of 0 to 10. Adding 10 to that will give you numbers in a range 10 to 20. You may use Math.ceil() or Math.floor() for rounding based on what you want the final range to be.

Recap: Math.random() always yields numbers from 0.0 to 1 (not including 1) and to get random numbers in a different range you simply transform that output by multiplying, adding, dividing, etc.