Add simple calculator program

main
蔡军仁 1 month ago
parent 039774b59a
commit 731317aa1d

@ -0,0 +1,62 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>简单计算器</title>
<style>
/* 简单的样式,可以根据需要自定义 */
body { font-family: Arial, sans-serif; }
.calculator { max-width: 300px; margin: 0 auto; padding: 20px; border: 1px solid #ccc; border-radius: 5px; }
input, button { width: 100%; padding: 10px; margin: 5px 0; }
</style>
</head>
<body>
<div class="calculator">
<input type="text" id="result" readonly>
<br>
<input type="number" id="num1" placeholder="输入第一个数字">
<select id="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="number" id="num2" placeholder="输入第二个数字">
<br>
<button onclick="calculate()">计算</button>
</div>
<script>
function calculate() {
const num1 = parseFloat(document.getElementById('num1').value);
const num2 = parseFloat(document.getElementById('num2').value);
const operator = document.getElementById('operator').value;
let result;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 === 0) {
result = '错误:除数不能为零';
} else {
result = num1 / num2;
}
break;
default:
result = '错误:无效运算符';
}
document.getElementById('result').value = result;
}
</script>
</body>
</html>
Loading…
Cancel
Save