使用VScode制作一个只要能实现加减乘除的简易计算器,要求使用button标签,和table标签
时间: 2024-05-22 10:16:22 浏览: 92
html+js实现简单的计算器代码(加减乘除)
5星 · 资源好评率100%
<!DOCTYPE html>
<html>
<head>
<title>简易计算器</title>
<style>
table {
margin: 0 auto;
border-collapse: collapse;
}
td {
padding: 10px;
border: 1px solid black;
text-align: center;
font-size: 20px;
font-weight: bold;
cursor: pointer;
}
#result {
text-align: center;
font-size: 30px;
font-weight: bold;
margin-top: 20px;
}
</style>
</head>
<body>
<table>
<tr>
<td colspan="2" id="result">0</td>
</tr>
<tr>
<td onclick="addNumber('7')">7</td>
<td onclick="addNumber('8')">8</td>
<td onclick="addNumber('9')">9</td>
<td onclick="calculate('+')">+</td>
</tr>
<tr>
<td onclick="addNumber('4')">4</td>
<td onclick="addNumber('5')">5</td>
<td onclick="addNumber('6')">6</td>
<td onclick="calculate('-')">-</td>
</tr>
<tr>
<td onclick="addNumber('1')">1</td>
<td onclick="addNumber('2')">2</td>
<td onclick="addNumber('3')">3</td>
<td onclick="calculate('*')">*</td>
</tr>
<tr>
<td onclick="addNumber('0')">0</td>
<td onclick="addNumber('.')">.</td>
<td onclick="clearAll()">C</td>
<td onclick="calculate('/')">/</td>
</tr>
<tr>
<td colspan="4" onclick="getResult()">=</td>
</tr>
</table>
<script>
let num1 = ''; // 第一个操作数
let num2 = ''; // 第二个操作数
let operator = ''; // 运算符
// 将输入的数字添加到当前操作数中
function addNumber(num) {
if (operator === '') {
num1 += num;
document.getElementById('result').innerHTML = num1;
} else {
num2 += num;
document.getElementById('result').innerHTML = num2;
}
}
// 清空所有操作数和运算符
function clearAll() {
num1 = '';
num2 = '';
operator = '';
document.getElementById('result').innerHTML = '0';
}
// 进行运算
function calculate(op) {
if (num1 === '') {
return;
}
operator = op;
}
// 获取计算结果
function getResult() {
if (num1 === '' || num2 === '' || operator === '') {
return;
}
let result = 0;
switch (operator) {
case '+':
result = parseFloat(num1) + parseFloat(num2);
break;
case '-':
result = parseFloat(num1) - parseFloat(num2);
break;
case '*':
result = parseFloat(num1) * parseFloat(num2);
break;
case '/':
result = parseFloat(num1) / parseFloat(num2);
break;
}
document.getElementById('result').innerHTML = result.toString();
num1 = result.toString();
num2 = '';
operator = '';
}
</script>
</body>
</html>
阅读全文