1. 계산기 구현하기
1-1. 기본 계산 기능 구현하기
function calculate(n1, operator, n2) {
let result = 0;
n1 = Number(n1);
n2 = Number(n2);
if (operator === '+') {
result = n1 + n2;
} else if (operator === '-') {
result = n1 - n2;
} else if (operator === '*') {
result = n1 * n2;
} else if (operator === '/') {
result = n1 / n2;
}
console.log(result);
return String(result);
}
if (target.matches('button')) {
if (action === 'number') {
console.log('숫자 ' + buttonContent + ' 버튼');
}
if (action === 'operator') {
console.log('연산자 ' + buttonContent + ' 버튼');
}
if (action === 'decimal') {
console.log('소수점 버튼');
}
if (action === 'clear') {
console.log('초기화 버튼');
}
if (action === 'calculate') {
console.log('계산 버튼');
}
}
1-2. 숫자 입력하기
if (action === 'number') {
if (firstOperend.textContent === '0') {
firstOperend.textContent = event.target.textContent;
} else {
secondOperend.textContent = event.target.textContent;
}
console.log('숫자 ' + buttonContent + ' 버튼');
}
1-3. 연산자 입력하기
if (action === 'operator') {
operator.textContent = event.target.textContent;
console.log('연산자 ' + buttonContent + ' 버튼');
}
1-4. 초기화 입력하기
if (action === 'clear') {
firstOperend.textContent = '0';
secondOperend.textContent = '0';
operator.textContent = '+';
calculatedResult.textContent = '0';
console.log('초기화 버튼');
}
1-5. 계산 결과 출력하기
if (action === 'calculate') {
calculatedResult.textContent = calculate(firstOperend.textContent, operator.textContent, secondOperend.textContent);
console.log('계산 버튼');
}