简体   繁体   中英

Generating random integer in range that doesn't start at zero

How can I generate numbers between 7 to 10? So far all I've figured out is generating in a range from 0-10:

Math.floor(Math.random()*11)
function getRandom(min, max) {
    return min + Math.floor(Math.random() * (max - min + 1));
}

for(var x = 0; x < 5; x++) {
    console.log(getRandom(7, 10));
}

Math.floor(7 + Math.random() * 4) will generate numbers from 7 to 10 inclusive.

Just say this:

Math.floor(Math.random()*4) + 7

This will generate a random number from 0-3 and then add 7 to it, to get 7-10.

7 + Math.floor(Math.random()*4)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM