/
aska
/
web-static-labs
Обзор
Документация
Войти
/
aska
/
web-static-labs
Код
Запросы
0
Задачи
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
html/lab5/task5/script.js
89 строк
3 KB
unknown
лабы 1 4 5
14 ноя 2025, 09:16
14 ноя 2025, 09:16
b757c12
Код
Авторство
О чём код?
'use strict'; document.addEventListener('DOMContentLoaded', () => { const display = document.getElementById('display'); const buttons = document.querySelectorAll('#buttons button'); const equals = document.getElementById('equals'); const clear = document.getElementById('clear'); let currentInput = ''; let operator = null; let firstOperand = null; const updateDisplay = () => { display.value = currentInput; }; buttons.forEach(button => { button.addEventListener('click', () => { const value = button.dataset.value; if (value === undefined && button.id !== 'equals' && button.id !== 'clear') { return; // Игнорируем кнопки без значения, кроме equals и clear } if (!isNaN(value) || value === '.') { currentInput += value; updateDisplay(); } else if (['+', '-', '*', '/'].includes(value)) { if (firstOperand === null) { firstOperand = parseFloat(currentInput); operator = value; currentInput = ''; updateDisplay(); } else { const result = calculate(firstOperand, parseFloat(currentInput), operator); firstOperand = result; operator = value; currentInput = ''; updateDisplay(); } } else if (button.id === 'equals') { if (firstOperand !== null && operator !== null && currentInput !== '') { const result = calculate(firstOperand, parseFloat(currentInput), operator); currentInput = String(result); updateDisplay(); firstOperand = null; operator = null; } } else if (button.id === 'clear') { currentInput = ''; operator = null; firstOperand = null; updateDisplay(); } else if (value === 'sqrt') { if (currentInput !== '') { const num = parseFloat(currentInput); if (num >= 0) { currentInput = String(Math.sqrt(num)); updateDisplay(); } else { currentInput = 'Error'; updateDisplay(); } } } else if (value === 'log') { if (currentInput !== '') { const num = parseFloat(currentInput); if (num > 0) { currentInput = String(Math.log10(num)); updateDisplay(); } else { currentInput = 'Error'; updateDisplay(); } } } }); }); const calculate = (a, b, op) => { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return b === 0 ? 'Error' : a / b; default: return NaN; } }; });