用JavaScript写一个计算器
时间: 2023-03-30 09:03:14 浏览: 149
好的,我可以回答这个问题。以下是一个简单的JavaScript计算器代码:
HTML代码:
```
<div>
<input type="text" id="result" readonly>
</div>
<div>
<button onclick="clearResult()">C</button>
<button onclick="deleteLast()">←</button>
<button onclick="calculate('/')">÷</button>
<button onclick="calculate('*')">x</button>
</div>
<div>
<button onclick="addNumber(7)">7</button>
<button onclick="addNumber(8)">8</button>
<button onclick="addNumber(9)">9</button>
<button onclick="calculate('-')">-</button>
</div>
<div>
<button onclick="addNumber(4)">4</button>
<button onclick="addNumber(5)">5</button>
<button onclick="addNumber(6)">6</button>
<button onclick="calculate('+')">+</button>
</div>
<div>
<button onclick="addNumber(1)">1</button>
<button onclick="addNumber(2)">2</button>
<button onclick="addNumber(3)">3</button>
<button onclick="calculate('=')">=</button>
</div>
<div>
<button onclick="addNumber()"></button>
<button onclick="addNumber('.')">.</button>
</div>
```
JavaScript代码:
```
let num1 = '';
let num2 = '';
let operator = '';
let result = document.getElementById('result');
function addNumber(num) {
if (operator === '') {
num1 += num;
result.value = num1;
} else {
num2 += num;
result.value = num2;
}
}
function calculate(op) {
if (num1 === '' || num2 === '') {
return;
}
let res;
switch (operator) {
case '+':
res = parseFloat(num1) + parseFloat(num2);
break;
case '-':
res = parseFloat(num1) - parseFloat(num2);
break;
case '*':
res = parseFloat(num1) * parseFloat(num2);
break;
case '/':
res = parseFloat(num1) / parseFloat(num2);
break;
}
num1 = res.toString();
num2 = '';
operator = op;
result.value = num1;
}
function clearResult() {
num1 = '';
num2 = '';
operator = '';
result.value = '';
}
function deleteLast() {
if (operator === '') {
num1 = num1.slice(, -1);
result.value = num1;
} else {
num2 = num2.slice(, -1);
result.value = num2;
}
}
```
这个计算器可以进行加、减、乘、除四则运算,也支持小数点和清空操作。
阅读全文