+ 1
What's the purpose of "+1" in (max - min +1)? In a range of (3, 7) how does the "+1" work I'm confused
function getRndInteger(min, max) { return Math.floor(Math.random() * (max - min + 1) ) + min; }
5 Antworten
+ 2
Math.random() returns a precision double value between 0 to 1.
Ex: 0.123456789
Multiplying a number N returns 0 to N (N not inclusive)
Math.floor returns a returns integer equalent value. Adding Min (ex:1) means value returned is between (Min, N+min)
Math.random() => 0 to 1
Math.random() * N => 0 to N
(Math.random() *N) +1 => 1 to N+1
Math.floor(Math.random() * (max - min + 1) ) + min;
=> returns between min to max, Integer values.
Hope it helps..
+ 1
JavaScript Random
https://www.w3schools.com/js/js_random.asp
// Returns a random integer from 0 to 9:
Math.floor(Math.random() * 10);
// Returns a random integer from 1 to 10:
Math.floor(Math.random() * 10) + 1;
+ 1
So it's basically means inclusive of the max number?
0
Thanks pal