오늘의 공부는 계산기 만들기><
기분 계산기 모형 틀이 있는 상태에서 JavaScript를 이용하여 Html에 계산기가 구동되도록 만드는 것
let count = 1;
function calculate(n1, operator, n2) {
let result = 0;
n1 = parseFloat(n1);
n2 = parseFloat(n2);
if (operator === '+'){
result = parseFloat(n1) + parseFloat(n2);
}
if (operator === '-'){
result = parseFloat(n1) - parseFloat(n2);
}
if (operator === '*'){
result = parseFloat(n1) * parseFloat(n2);
}
if (operator === '/'){
result = parseFloat(n1) / parseFloat(n2);
}
// TODO : n1과 n2를 operator에 따라 계산하는 함수를 만드세요.
// ex) 입력값이 n1 : '1', operator : '+', n2 : '2' 인 경우, 3이 리턴됩니다.
return String(result);
}
parseFloat()
문자열을 숫자로 변경하는 함수를 넣어 계산의 값이 숫자로 되게 만든다. 소수점까지 나타내기 때문에 parseInt()
대신 넣었다.
+Number()
함수도 문자를 숫자로 바꿔줄 수 있는데 문자형 숫자 외에 다른 문자가 들어가면 NaN이 뜬다.
buttons.addEventListener('click', function (event) {
// 버튼을 눌렀을 때 작동하는 함수입니다.
const target = event.target; // 클릭된 HTML 엘리먼트의 정보가 저장되어 있습니다.
const action = target.classList[0]; // 클릭된 HTML 엘리먼트에 클레스 정보를 가져옵니다.
const buttonContent = target.textContent; // 클릭된 HTML 엘리먼트의 텍스트 정보를 가져옵니다.
// ! 위 코드(Line 19 - 21)는 수정하지 마세요.
if (target.matches('button')) {
// TODO : 계산기가 작동할 수 있도록 아래 코드를 수정하세요. 작성되어 있는 조건문과 console.log를 활용하시면 쉽게 문제를 풀 수 있습니다.
// 클릭된 HTML 엘리먼트가 button이면
if (action === 'number') {
if(firstOperend.textContent === '0') {
console.log('숫자 ' + buttonContent + ' 버튼');
firstOperend.textContent =buttonContent;
}
else {
console.log('숫자 ' + buttonContent + ' 버튼');
secondOperend.textContent =buttonContent;
}
// 그리고 버튼의 클레스가 number이면
// 아래 코드가 작동됩니다.
}
if (action === 'operator') {
console.log('연산자 ' + buttonContent + ' 버튼');
operator.textContent=buttonContent;
}
if (action === 'decimal') {
// console.log('소수점 버튼');
}
if (action === 'clear') {
console.log('초기화 버튼');
firstOperend.textContent = '0';
operator.textContent = '+';
secondOperend.textContent = '0';
calculatedResult.textContent = '0';
}
if (action === 'calculate') {
console.log('계산 버튼');
calculatedResult.textContent = calculate(firstOperend.textContent, operator.textContent, secondOperend.textContent)
}
}
});
위의 코드들을 통해 첫 번째 숫자와 두 번째 숫자를 디스플레이 상에 표시하게 만들고 calculate
함수를 통해 계산이 되게 코딩을 했다.