본문 바로가기
Frontend/JavaScript

07.JavaScript Math객체

by 개발개발빈이 2022. 4. 27.

○ Math 객체

    - 수학과 관련되어 있는 객체

    - 수학에서 자주 사용되는 상수, 함수들 사용 가능

    - 사용법 : Math.변수명 | Math.함수()

document.write(Math.E);		//2.718281828459045
document.write(Math.PI);	//3.141592653589793
            
document.write(Math.abs(-3));               //3 절댓값  
document.write(Math.max(7, 5, 9, 12));      //12 최댓값
document.write(Math.min(7, 5, 9, 12));      //7 최솟값
document.write(Math.pow(2, 4));             //16 거듭제곱(밑, 지수)

 

○ 반올림, 올림, 버림

    - 반올림 :  소수점 첫 번째 자리에서 반올림 → Math.round(숫자)

    - 올림 : 소수점 첫 번째 자리에서 올림 → Math.ceil(숫자)

    - 버림 : 소수점 첫 번째 자리에서 버림 → Math.floor(숫자)

// 소수점 반올림
document.write(Math.round(4.9));    //5            
document.write(Math.round(4.4));    //4
document.write(Math.round(-4.2));   //-4

// 소수점 올림
document.write(Math.ceil(4.9));    //5
document.write(Math.ceil(4.4));    //5
document.write(Math.ceil(-4.2));   //-4

// 소수점 버림
document.write(Math.floor(4.9));   //4
document.write(Math.floor(4.4));   //4
document.write(Math.floor(-4.2));  //-5

 

○ 난수 발생

    - 난수 : 무작위로 발생하는 수

    - random() : 0.0이상 1이하의 수가 무작위로 발생

document.write(Math.random());		//0이상 1미만 난수 발생(새로고침할 때마다 달라짐)
document.write(Math.random()*2);	//0이상 2미만 난수 발생

//소수점없이 정수값만 가져옴
document.write(parseInt(Math.random()*2));  //0, 1
document.write(parseInt(Math.random()*4));  //0, 1, 2, 3

 

● PRACTICE 연습문제

    - 난수 발생 관련 연습 문제

        Q1) 주사위 범위(1~6) 내의 수만 발생시키시오

        Q2) 로또 번호 범위(1~45) 사이의 수만 발생시키시오

//Q1
document.write(parseInt((Math.random()*6)+1));

//Q2
document.write(parseInt((Math.random()*45)+1));

 

댓글