How to get a random number in a given interval in JavaScript
Task: you need to write a JavaScript function selfrandom(a,b:int):int
that returns a random number in the interval from a to b
for example: selfrandom(12,396);
returns 254
1
2 answers
function selfRandom(min, max)
{
return Math.floor(Math.random() * (max - min + 1)) + min;
}
4
Author: Spectre, 2011-12-31 11:09:29
Random number from 0 to 1: Math.random()
Rounding a number:
- Up to more:
Math.round( 1.1 ) = 2
- To the nearest one:
Math.ceil( 1.5 ) = 2, Math.ceil( 1.1 ) = 1
- Up to less than
Math.floor( 1.9 ) = 1
or~~( 1.9 ) = 1
Declaring a function of 2 variables:
function my_fn ( a, b ){
var res = 0;
//действия
return res;
}
0
Author: timka_s, 2011-12-31 11:08:57