/
Coderdev
/
web-static-labs
Обзор
Документация
Войти
/
Coderdev
/
web-static-labs
Код
Запросы
0
Задачи
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
html/lab5/task5/calc.js
151 строка
5 KB
Coderdev
1
12 май 2026, 12:37
12 май 2026, 12:37
d8ecd0f
Код
Авторство
О чём код?
'use strict'; const $ = (id) => document.getElementById(id); 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': return (a > 0 && baseValue > 0 && baseValue !== 1) ? Math.log(a) / Math.log(baseValue) : NaN; default: return NaN; } } document.addEventListener('DOMContentLoaded', () => { const display = $('display'); const history = $('history'); const baseInput = $('base'); const roundCheck = $('round'); let currentInput = '0'; let prevInput = null; let currentOp = null; // $('round').addEventListener('change', () => { let res = parseFloat(display.value); // Если на экране число и галочка нажата — округляем if (!isNaN(res) && $('round').checked) { display.value = parseFloat(res.toFixed(3)); }}) document.querySelectorAll('.btn-num').forEach(btn => { btn.onclick = () => { const val = btn.innerText; if (currentInput === '0' && val !== '.') currentInput = val; else if (val === '.' && currentInput.includes('.')) return; else currentInput += val; display.value = currentInput; }; }); document.querySelector('.btn-clear').onclick = () => { currentInput = '0'; prevInput = null; currentOp = null; display.value = '0'; history.innerText = ''; baseInput.style.display = 'none'; }; document.querySelectorAll('.btn-op').forEach(btn => { btn.onclick = () => { const op = btn.dataset.op; if (op === 'log') { // Для логарифма: просто показываем поле и запоминаем операцию baseInput.style.display = 'inline'; currentOp = 'log'; history.innerText = `log по основанию... от ${currentInput}`; // НЕ вызываем вычисление сразу! } else if (op === 'sqrt') { // Корень можно вычислить сразу, так как не нужно второе число currentOp = 'sqrt'; performCalculation('sqrt'); } else { // Для обычных операций (+, -, *, /) baseInput.style.display = 'none'; prevInput = currentInput; currentOp = op; history.innerText = `${prevInput} ${currentOp}`; currentInput = '0'; } }; }); // Кнопка "=" $('doCalc').onclick = () => { if (currentOp) { performCalculation(currentOp); } }; function performCalculation(op) { // 'a' - это либо число из истории (для +,-,*,/), либо текущее число с экрана (для log, sqrt) const a = prevInput !== null ? parseFloat(prevInput) : parseFloat(display.value); const b = parseFloat(display.value); const baseVal = parseFloat(baseInput.value); // Валидация перед вычислением if (op === 'log' && (isNaN(baseVal) || baseVal <= 0 || baseVal === 1)) { display.value = 'Основание!'; // Подсказка, что забыли ввести основание return; } let res = calc(a, op, b, baseVal); if (Number.isNaN(res)) { display.value = 'Ошибка'; } else { if (roundCheck && roundCheck.checked) { res = Number(res.toFixed(3)); } display.value = res; currentInput = String(res); prevInput = null; currentOp = null; history.innerText = ''; // Скрываем поле основания после успешного счета, если хочешь // baseInput.style.display = 'none'; } } $('doCalc').onclick = () => { if (currentOp || currentOp === null) { performCalculation(currentOp); } }; function performCalculation(op) { // Получаем числа const a = prevInput !== null ? parseFloat(prevInput) : parseFloat(display.value); const b = parseFloat(display.value); const baseVal = parseFloat($('base').value); const isRound = $('round').checked; // Прямая проверка чекбокса let res = calc(a, op, b, baseVal); if (Number.isNaN(res)) { display.value = 'Ошибка'; } else { // Логика округления if (isRound) { // toFixed возвращает строку, поэтому оборачиваем в Number, // чтобы убрать лишние нули в конце (например, 5.000 -> 5) res = parseFloat(res.toFixed(3)); } display.value = res; currentInput = String(res); prevInput = null; currentOp = null; history.innerText = ''; } } });