59 lines
1.6 KiB
JavaScript
59 lines
1.6 KiB
JavaScript
let currentInput = '';
|
|
let previousInput = '';
|
|
let operator = null;
|
|
|
|
function appendToDisplay(value) {
|
|
currentInput += value;
|
|
document.getElementById('display').value = currentInput;
|
|
}
|
|
|
|
function setOperation(op) {
|
|
if (currentInput === '') return;
|
|
if (previousInput !== '') {
|
|
calculateResult();
|
|
}
|
|
operator = op;
|
|
previousInput = currentInput;
|
|
currentInput = '';
|
|
|
|
const operationButtons = document.querySelectorAll('.button');
|
|
operationButtons.forEach(button => button.classList.remove('active'));
|
|
|
|
const activeButton = document.getElementById(op);
|
|
if (activeButton) {
|
|
activeButton.classList.add('active');
|
|
}
|
|
}
|
|
|
|
function calculateResult() {
|
|
if (previousInput === '' || currentInput === '') return;
|
|
let result;
|
|
const prev = parseFloat(previousInput);
|
|
const current = parseFloat(currentInput);
|
|
if (operator === '+') {
|
|
result = prev + current;
|
|
} else if (operator === '-') {
|
|
result = prev - current;
|
|
} else if (operator === '*') {
|
|
result = prev * current;
|
|
} else if (operator === '/') {
|
|
if (current === 0) {
|
|
alert("Errore: divisione per zero!");
|
|
return;
|
|
}
|
|
result = prev / current;
|
|
}
|
|
document.getElementById('display').value = result;
|
|
currentInput = result.toString();
|
|
previousInput = '';
|
|
}
|
|
|
|
function clearDisplay() {
|
|
currentInput = '';
|
|
previousInput = '';
|
|
operator = null;
|
|
document.getElementById('display').value = '';
|
|
|
|
const operationButtons = document.querySelectorAll('.button');
|
|
operationButtons.forEach(button => button.classList.remove('active'));
|
|
} |