각진 세상에 둥근 춤을 추자

[JavaScript] 수학 객체 본문

JavaScript

[JavaScript] 수학 객체

circle.j 2022. 10. 9. 16:51

 

 

자바스크립트 내장 객체에는 수학과 관련된 기능과 속성을 제공하는 수학 객체(Math Object)가 있다. 

 

종류 설명
Math.abs(숫자) 숫자의 절댓값을 반환
Math.max(숫자1, 숫자2, 숫자3, 숫자4) 숫자 중 가장 큰 값을 반환
Math.min(숫자1, 숫자2, 숫자3, 숫자4) 숫자 중 가장 작은 값을 반환
Math.pow(숫자, 제곱값) 숫자의 거듭제곱을 반환
Math.random() 0~1 사이의 난수를 반환
Math.round(숫자) 소수점 첫째 자리에서 반올림하여 정수를 반환
Math.ceil(숫자) 소수점 첫째 자리에서 무조건 올림하여 정수를 반환
Math.floor(숫자) 소수점 첫째 자리에서 무조건 내림하여 정수를 반환
Math.sqrt(숫자) 숫자의 제곱근값을 반환
Math.PI 원주율 상수를 반환

 

예제를 통해 수학 객체에 대해 이해해 본다. 

[예제1]

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>수학 객체</title>
</head>
<body>
    <script>
        let num = 2.1234;

        let maxNum = Math.max(10,5,8,30);
        let minNum = Math.min(10,5,8,30);
        let roundNum = Math.round(num)
        let floorNum = Math.floor(num);
        let ceilNum = Math.ceil(num);
        let rndNum = Math.random();
        let piNum = Math.PI;

        document.write('최댓값: ' + maxNum + '<br/>');
        document.write('최솟값: ' + minNum + '<br/>');
        document.write('반올림값: ' + roundNum + '<br/>');
        document.write('내림값: ' + floorNum + '<br/>');
        document.write('올림값: ' + ceilNum + '<br/>');
        document.write('랜덤값: ' + rndNum + '<br/>');
        document.write('원주율값: ' + piNum + '<br/>');
        
    </script>
</body>
</html>

 

 

Math.random() 메서드는 0과 1 사이에서 난수를 발생시키는 것을 알 수 있다. 

그렇다면 0과 1 사이가 아닌 숫자의 구간에서 난수를 반환받으려면 어떻게 해야 할까?

// 0부터 1까지 난수 반환
Math.random()

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

// 난수를 발생하여 원하는 구간 정수의 값 구하기
Math.floor(Math.random()*(최댓값-최솟값+1))+최솟값;

// 0부터 10까지 난수 반환(소수점 값 제거)
Math.floor(Math.random()*11);

// 0부터 30까지의 난수 반환(소수점 값 제거)
Math.floor(Math.random()*31);

// 120부터 150까지 난수 반환(소수점 값 제거)
Math.floor(Math.random()*31)+120;

 

[예제2] 가위바위보 

웹사이트 방문 시 나타나는 창에 방문자가 '가위, 바위, 보'를 적어 컴퓨터가 내려는 가위, 바위, 보를 추측해 맞춘다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>수학객체: 가위바위보</title>
</head>
<body>
    <script>
        document.write("<h1>가위 바위 보~?</h1>")

        let game = prompt("Game: 가위 바위 보!","");
        let gameNum;
        switch (game){
            case "가위": gameNum = 1; break;
            case "바위": gameNum = 2; break;
            case "보" : gameNum = 3; break;
            default: alert("가위 바위 보 중 하나를 입력해 주십시오.");
                     location.reload();
        }
        let com = Math.ceil(Math.random()*3);
        
        if (gameNum == com){
            document.write("<h3> 맞췄습니다! </h3>");
        }else {
            document.write("<h3> 틀렸습니다.! </h3>");
        }

    </script>
</body>
</html>

 

 

 

 

 

'JavaScript' 카테고리의 다른 글

[JS] 문자열 객체  (0) 2022.10.09
[JS] 배열 객체  (0) 2022.10.09
[JavaScript] 객체  (0) 2022.10.08
[JavaScript] 반복문  (0) 2022.10.08
[JavaScript] 선택문  (0) 2022.10.08