You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Git/final/script.js

89 lines
2.2 KiB

2 months ago
let displayValue = '0'; // 显示屏上的内容
let firstNumber = null; // 第一个数字
let secondNumber = null; // 第二个数字
let operation = null; // 运算符
let waitingForSecondNumber = false;
// 更新显示
function updateDisplay() {
const display = document.getElementById('display');
display.innerText = displayValue;
}
// 添加数字
function appendNumber(number) {
if (waitingForSecondNumber) {
displayValue = number.toString();
waitingForSecondNumber = false;
} else {
displayValue = displayValue === '0' ? number.toString() : displayValue + number.toString();
}
updateDisplay();
}
// 设置运算符
function setOperation(op) {
if (firstNumber === null) {
firstNumber = parseFloat(displayValue);
} else if (operation) {
secondNumber = parseFloat(displayValue);
firstNumber = performCalculation(firstNumber, secondNumber, operation);
displayValue = firstNumber.toString();
updateDisplay();
}
operation = op;
waitingForSecondNumber = true;
}
// 计算结果
function calculate() {
if (operation && !waitingForSecondNumber) {
secondNumber = parseFloat(displayValue);
displayValue = performCalculation(firstNumber, secondNumber, operation).toString();
firstNumber = null;
secondNumber = null;
operation = null;
updateDisplay();
}
}
// 执行计算
function performCalculation(num1, num2, operator) {
switch (operator) {
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
return num2 !== 0 ? num1 / num2 : '错误';
default:
return num2;
}
}
// 百分号处理
function percent() {
displayValue = (parseFloat(displayValue) / 100).toString();
updateDisplay();
}
// 添加小数点
function appendSymbol(symbol) {
if (!displayValue.includes(symbol)) {
displayValue += symbol;
updateDisplay();
}
}
// 清除显示
function clearDisplay() {
displayValue = '0';
firstNumber = null;
secondNumber = null;
operation = null;
waitingForSecondNumber = false;
updateDisplay();
}