코밍이의 하루

[JS] 내장 객체 - 수학 객체 본문

웹언어 공부/JS

[JS] 내장 객체 - 수학 객체

코밍이 2021. 8. 11. 23:02

1. 개발 환경

구분 내용
사용 언어 HTML5, JS
개발환경 Visual Studio Code
참고 도서 [Do it] 자바스크립트 + 제이쿼리 입문
웹브라우저 Chrome

 

2. 주요 문법

1) 수학 객체

- 수학과 관련된 기능과 속성을 제공

 

2) 수학 객체의 메소드 및 상수

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

 

3) Math.random() 활용

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

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

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

 

3. 소스 코드 및 실행 결과

- math_ob1_test.html

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

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

			document.write(maxNum, "<br>");
			document.write(minNUum, "<br>");
			document.write(roundNum, "<br>");
			document.write(floorNum, "<br>");
			document.write(ceilNum, "<br>");
			document.write(rndNum, "<br>");
			document.write(piNum, "<br>");

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

math_ob1_test.html

 

- math_ob2_test.html

<!DOCTYPE html>
<html lang="ko">
	<head>
		<meta charset = "UTF-8">
		<title> 수학객체 </title>
		<script>
			document.write("<h1>컴퓨터 가위, 바위, 보 맞추기</h1>");

			var game = prompt("가위, 바위, 보 중 선택하세요?", "가위");
			var gameNum;
			switch(game){
				case "가위":
					gameNum = 1; break;
				case "바위":
					gameNum = 2; break;
				case "보":
					gameNum = 3; break;
				default: 
					alert("잘못 작성했습니다.");
					location.reload();	
			}

			var com = Math.ceil(Math.random() * 3);
			document.write("<img src=\"images/math_img_" + com + ".jpg\">");

			if(gameNum == com){
				document.write("<img src=\"images/game_1.jpg\">");
			} else {
				document.write("<img src=\"images/game_2.jpg\">");
			}
		</script>
	</head>
	<body>
	</body>
</html>

math_ob2_test.html

'웹언어 공부 > JS' 카테고리의 다른 글

[JS] 내장 객체 - 문자열 객체  (0) 2021.08.11
[JS] 내장 객체 - 배열 객체  (0) 2021.08.11
[JS] 내장 객체 - 날짜 정보 객체  (0) 2021.08.11
[JS] 내장 객체 - 내장 객체 생성하기  (0) 2021.08.11
[JS] 객체  (0) 2021.08.11