개발/javascript

[JS 스터디] 랜덤 숫자 생성 - Math.random();

JH._.kim 2022. 11. 16. 15:37

랜덤한 2개의 숫자 생성 후 사칙연산 결과 출력하기

let numA = Math.floor((Math.random() * 10) + 1);
let numB = Math.floor((Math.random() * 20) + 1);

`두 숫자는 ${numA}, ${numB}입니다. 
두 수의 합은  ${numA + numB}입니다. 
두 수의 차는 ${numA - numB}입니다. 
두 수의 곱은 ${numA * numB}입니다. 
큰 수를 작은 수로 나누면 ${numA / numB}입니다.`

Math.random()

0 이상 ~ 1 미만의 난수를 반환한다.

 

1. a 이상 ~ b 미만의 난수 구하기

Math.random() * (max - min) + min;

 

ex) 0 이상 ~ 9 미만의 난수

Math.random() * 9;

0 * 9 = 0; → min

0.394857... * 9 = 3.553713...

0.999999... * 9 = 8.999999... → max

 

ex) 43 이상 79 미만의 난수

Math.random() * (79 - 43) + 43;

0 * 36 + 43 = 43; → min

0.394857... * 36 + 43 = 57.214852...

0.999999... * 36 + 43 = 78.999964... → max

 

2. 정수로 반환하고자 하는 경우

Math.floor() → 소수점 첫째 자리에서 내림

 

3. a 이상 ~ b 이하의 난수 구하기

Math.random() * (max - min + 1) + min; 

 

 

연산자 랜덤으로 출력 및 사칙연산 함수로 결과값 출력하기

const optrArray = ['+', '-', '/', '*'];
let randomOptr = Math.floor(Math.random() * optrArray.length);
let optr = optrArray[randomOptr];
function calculateRandomNum(a, b, operator){
    switch(operator){
        case '+' :
            return a + b;
            break;
        case '-' :
            return a - b;
            break;
        case '/' :
            return a / b;
            break;
        case '*' :
            return a * b;
            break;
    }
}
calculateRandomNum(numA, numB, optr);
728x90