html 简易计算器
时间: 2023-11-23 22:58:00 浏览: 87
以下是一个简单的HTML计算器的示例,它使用逆波兰表达式来实现加减乘除的计算。你可以将以下代码保存为.html文件并在浏览器中打开来查看效果。
```html
<!DOCTYPE html>
<html>
<head>
<title>简易计算器</title>
<meta charset="utf-8">
<style type="text/css">
body {
background-color: #f5f5f5;
font-family: Arial, sans-serif;
}
#calculator {
width: 300px;
margin: 50px auto;
background-color: #fff;
border: 1px solid #ccc;
padding: 10px;
box-shadow: 0 0 10px #ccc;
}
#calculator input[type="button"] {
width: 50px;
height: 50px;
font-size: 20px;
margin: 5px;
background-color: #eee;
border: 1px solid #ccc;
border-radius: 5px;
box-shadow: 0 0 5px #ccc;
cursor: pointer;
}
#calculator input[type="text"] {
width: 100%;
height: 50px;
font-size: 20px;
margin-bottom: 5px;
padding: 5px;
box-sizing: border-box;
border: 1px solid #ccc;
border-radius: 5px;
box-shadow: 0 0 5px #ccc;
}
</style>
</head>
<body>
<div id="calculator">
<input type="text" id="result" readonly>
<input type="button" value="7" onclick="addNumber('7')">
<input type="button" value="8" onclick="addNumber('8')">
<input type="button" value="9" onclick="addNumber('9')">
<input type="button" value="+" onclick="addOperator('+')">
<br>
<input type="button" value="4" onclick="addNumber('4')">
<input type="button" value="5" onclick="addNumber('5')">
<input type="button" value="6" onclick="addNumber('6')">
<input type="button" value="-" onclick="addOperator('-')">
<br>
<input type="button" value="1" onclick="addNumber('1')">
<input type="button" value="2" onclick="addNumber('2')">
<input type="button" value="3" onclick="addNumber('3')">
<input type="button" value="*" onclick="addOperator('*')">
<br>
<input type="button" value="0" onclick="addNumber('0')">
<input type="button" value="." onclick="addNumber('.')">
<input type="button" value="=" onclick="calculate()">
<input type="button" value="/" onclick="addOperator('/')">
<br>
<input type="button" value="C" onclick="clearResult()">
</div>
<script type="text/javascript">
var stack = [];
function addNumber(num) {
document.getElementById("result").value += num;
}
function addOperator(op) {
if (document.getElementById("result").value != "") {
stack.push(parseFloat(document.getElementById("result").value));
stack.push(op);
document.getElementById("result").value = "";
}
}
function calculate() {
if (document.getElementById("result").value != "") {
stack.push(parseFloat(document.getElementById("result").value));
document.getElementById("result").value = "";
}
var result = stack[0];
for (var i = 1; i < stack.length; i += 2) {
switch (stack[i]) {
case "+":
result += stack[i + 1];
break;
case "-":
result -= stack[i + 1];
break;
case "*":
result *= stack[i + 1];
break;
case "/":
result /= stack[i + 1];
break;
}
}
document.getElementById("result").value = result;
stack = [];
}
function clearResult() {
document.getElementById("result").value = "";
stack = [];
}
</script>
</body>
</html>
```
阅读全文