실제 시나리오에서 Math 객체 메서드 적용
이 단계에서는 실제 시나리오에서 Math 객체 메서드의 실용적인 적용을 탐구합니다. math-demo.html 파일을 열고 다음 코드를 추가하여 실용적인 사용 사례를 시연합니다.
// Practical Scenarios with Math Object Methods
// 1. Calculate Discount Price
function calculateDiscount(originalPrice, discountPercentage) {
let discountAmount = originalPrice * (discountPercentage / 100);
let finalPrice = originalPrice - discountAmount;
displayOutput(`Original Price: $${originalPrice.toFixed(2)}`);
displayOutput(
`Discount (${discountPercentage}%): $${discountAmount.toFixed(2)}`
);
displayOutput(`Final Price: $${finalPrice.toFixed(2)}`);
return finalPrice;
}
calculateDiscount(100, 20);
// 2. Circle Area Calculator
function calculateCircleArea(radius) {
let area = Math.PI * Math.pow(radius, 2);
displayOutput(`Circle Radius: ${radius}`);
displayOutput(`Circle Area: ${area.toFixed(2)} sq units`);
return area;
}
calculateCircleArea(5);
// 3. Temperature Converter (Celsius to Fahrenheit)
function celsiusToFahrenheit(celsius) {
let fahrenheit = Math.round((celsius * 9) / 5 + 32);
displayOutput(`${celsius}°C is ${fahrenheit}°F`);
return fahrenheit;
}
celsiusToFahrenheit(25);
// 4. Hypotenuse Calculator
function calculateHypotenuse(a, b) {
let hypotenuse = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
displayOutput(`Triangle Sides: ${a}, ${b}`);
displayOutput(`Hypotenuse Length: ${hypotenuse.toFixed(2)}`);
return hypotenuse;
}
calculateHypotenuse(3, 4);
// 5. Random Score Generator for a Quiz
function generateQuizScores(numberOfStudents) {
displayOutput(`Quiz Scores for ${numberOfStudents} students:`);
for (let i = 1; i <= numberOfStudents; i++) {
let score = Math.floor(Math.random() * 51) + 50; // Scores between 50-100
displayOutput(`Student ${i}: ${score}`);
}
}
generateQuizScores(5);
예시 출력은 다음과 같습니다.
Original Price: $100.00
Discount (20%): $20.00
Final Price: $80.00
Circle Radius: 5
Circle Area: 78.54 sq units
25°C is 77°F
Triangle Sides: 3, 4
Hypotenuse Length: 5.00
Quiz Scores for 5 students:
Student 1: 75
Student 2: 92
Student 3: 63
Student 4: 87
Student 5: 69
이 시연은 Math 객체 메서드를 다양한 실용적인 시나리오에 적용하는 방법을 보여줍니다.
- 할인 계산
- 기하학적 면적 계산
- 온도 변환
- 빗변 길이 찾기
- 난수 점수 생성