Math. ~(), 랜덤함수 예제
Math 객체
- 자바스크립트에서 제공하는 수학 관련 메서드와 상수를 담고 있는 내장객체
1. Math.abs(x);
- 주어진 x값의 절대값을 반환
ex) Math.abs(-10); // 10
2. Math.ceil(x);
- 주어진 x값을 올림하여 가장 가까운 정수를 반환
ex) Math.ceil(4.3); // 5
3. Math.floor(x);
- 주어진 x값을 내림하여 가장 가까운 정수를 반환
ex) Math.floor(4.7) // 4
4. Math.round(x);
- 주어진 x값을 반올림 하여 가장 가까운 정수를 반환
ex) Math.round(4.3); // 4
5. Math.max(...values);
- 주어진 숫자 중 가장 큰 값을 반환
ex) Math.max(1,5,10); // 10
6. Math.min(...values);
- 주어진 숫자 중 가장 작은 값을 반환
ex) Math.min(1,5,10); // 1
7. Math.pow(base, exponent);
- base를 exponent로 거듭제곱한 값을 반환
ex) Math.pow(2,3); // 2의 3승 : 8
8. Math.sqrt(x);
- 주어진 숫자의 제곱근을 반환
ex) Math.sqrt(16); // 4
9. Math.cbrt(x);
- 주어진 숫자의 세제곱근을 반환
ex) Math.cbrt(27); // 3
10. Math.log(x);
- 주어진 숫자의 자연로그(밑이 e인 로그)를 반환
ex) Math.log(Math.E); // 1
11. Math.exp(x);
- e의 x제곱을 반환
ex) Math.exp(1); // 2.7182...( e )
12. Math.sin(x);
- 주어진 각도의 사인 값을 반환
ex) Math.sin(Math.PI / 2); // 1
13. Math.cos(x);
- 주어진 각도의 코사인 값을 반환
14. Math.tan(x);
- 주어진 각도의 탄젠트 값을 반환
15. Math.random();
- 0 이상 1 미만의 난수를 반환
const randomValue = Math.random();
console.log(randomValue); // 0 이상 1 미만의 난수 출력
Math.random() * 5 => 0 ~ 5 사이의 값
Math.random() * 5 + 2 => 2 ~ 7 사이의 값
Math.floor(Math.random() * 5 + 2) // 랜덤 소수점 값을 정수로 생성
- 랜덤 정수 생성 함수
// Math.random()는 0 <= x < 1 의 실수가 생성됨
// 2 ~ 7 미만의 정수 생성하려면~ 7-2 = 5 5개의 정수가 필요
function getRandomInt(min, max){
return Math.floor(Math.random() * (max - min)) + min;
}
랜덤함수 사용
- 랜덤으로 배경색 뿌리기
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.test{width:100px;height:100px;margin-top:20px;}
</style>
</head>
<body>
<h1>랜덤 색상 생성기</h1>
<button onclick="generateRandomColor()">랜덤 색상 생성</button>
<div class="test"></div>
<script>
// rgb에 랜덤으로 값 주기
function getRandomColor(){
const r = Math.floor(Math.random()*256);
const g = Math.floor(Math.random()*256);
const b = Math.floor(Math.random()*256);
return `rgb(${r},${g},${b})`;
}
function generateRandomColor(){
const randomColor = getRandomColor();
document.getElementsByClassName('test')[0].style.backgroundColor = randomColor;
}
</script>
</body>
</html>
계산식
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{margin:20px;font-family:Arial, sans-serif;}
input, button{margin:10px 0;}
</style>
</head>
<body>
<h1>그림자 길이 계산기</h1>
<p>태양의 고도 각도와 물체의 높이를 입력하여 그림자의 길이를 계산합니다.</p>
<label for="angle">태양의 고도 각도: </label>
<input id="angle" type="number" placeholder="예: 45">
<label for="height">물체의 높이(미터): </label>
<input id="height" type="number" placeholder="예: 2">
<button onclick="calculateShadow()">그림자 길이 계산</button>
<h2>결과</h2>
<p id="result">그림자 길이가 여기에 표시됩니다.</p>
<script>
function calculateShadow(){
const angle = parseFloat(document.getElementById('angle').value); // 문자열을 정수로 반환
const height = parseFloat(document.getElementById('height').value);
if(isNaN(angle) || angle <= 0 || isNaN(height) || height <= 0){
document.getElementById('result').innerText = '올바른 값을 입력하세요.';
}
const angleInRadians = angle * (Math.PI / 180);
const shadowLength = height / Math.tan(angleInRadians);
document.getElementById('result').innerText = `그림자의 길이: ${shadowLength.toFixed(2)} 미터`;
}
</script>
</body>
</html>