/
Coderdev
/
web-static-labs
Обзор
Документация
Войти
/
Coderdev
/
web-static-labs
Код
Запросы
0
Задачи
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
html/lab4/task1/calc.js
88 строк
3 KB
Coderdev
1
12 май 2026, 12:37
12 май 2026, 12:37
d8ecd0f
Код
Авторство
О чём код?
'use strict'; // Пример 1. Калькулятор [cite: 37] const $ = (id) => document.getElementById(id); const readNumber = (el) => { const raw = String(el.value).trim(); return raw === '' ? NaN : Number(raw); }; // Функция вычисления результата function calc(a, op, b, baseValue) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return b === 0 ? NaN : a / b; case 'sqrt': return a >= 0 ? Math.sqrt(a) : NaN; case 'log': // Формула логарифма: ln(a) / ln(base) return (a > 0 && baseValue > 0 && baseValue !== 1) ? Math.log(a) / Math.log(baseValue) : NaN; default: return NaN; } } document.addEventListener('DOMContentLoaded', () => { const operator = $('operator'); const operand1 = $('operand1'); const operand2 = $('operand2'); const baseInput = $('base'); const roundCheck = $('round'); // Чекбокс "Округлить" из твоего HTML const doCalc = $('doCalc'); const resultEl = $('result'); // Логика блокировки и показа доп. поля (Задание 1) operator.addEventListener('change', () => { const op = operator.value; if (op === 'sqrt' || op === 'log') { operand2.disabled = true; operand2.value = ''; baseInput.style.display = (op === 'log') ? 'inline' : 'none'; } else { operand2.disabled = false; baseInput.style.display = 'none'; } }); doCalc.addEventListener('click', () => { const a = readNumber(operand1); const b = readNumber(operand2); const baseVal = readNumber(baseInput); const op = operator.value; // Валидация if (Number.isNaN(a)) { resultEl.textContent = 'Введите первый операнд'; return; } // Для sqrt и log не проверяем b, но для log проверяем base if (!operand2.disabled && Number.isNaN(b)) { resultEl.textContent = 'Введите второй операнд'; return; } if (op === 'log' && (Number.isNaN(baseVal) || baseVal <= 0 || baseVal === 1)) { resultEl.textContent = 'Некорректное основание'; return; } if (op === '/' && b === 0) { resultEl.textContent = 'Деление на ноль невозможно'; return; } // Вычисление [cite: 81] let res = calc(a, op, b, baseVal); if (Number.isNaN(res)) { resultEl.textContent = 'Не удалось вычислить'; } else { if (roundCheck && roundCheck.checked) { res = Number(res.toFixed(3)); } resultEl.textContent = String(res); } }); });