[js]난수 Math.random

2022. 5. 26. 16:16js

Math.random()   //0~1 사이의 난수를 반환

 

Math.random()*10;   //0부터 10까지 실수로 난수를 반환

 

>> 정수로만 난수를 반환하려면 floor()를 사용해야 함

 

Math.floor(Math.random()*11);   //0부터 10까지 난수를 발생하여 소수점 값을 제거 

floor는 값을 내리기 때문에 하나 더 많게

 

 

 


난수를 발생하여 원하는 구간 정수의 값 구하기

Math.floor(Math.random()*(최댓값 -  최솟값 +1))+최솟값;

 

120~150 사이의 난수를 정수로만 발생하기

Math.floor(Math.random()*31);            //0부터 30까지 정수로 난수를 발생

Math.floor(Math.random()*31)+120;   //120부터 150까지 정수로 난수를 발생