使用JavaScript语言做一个简易计算机
时间: 2023-05-26 19:06:48 浏览: 102
以下是一个简单的HTML代码和JavaScript代码,可以实现一个基本的计算器功能。
HTML代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>计算器</title>
</head>
<body>
<h1>计算器</h1>
<input type="text" id="result" placeholder="输入结果">
<br><br>
<button onclick="addNumber(1)">1</button>
<button onclick="addNumber(2)">2</button>
<button onclick="addNumber(3)">3</button>
<button onclick="addOperator('+')">+</button>
<br>
<button onclick="addNumber(4)">4</button>
<button onclick="addNumber(5)">5</button>
<button onclick="addNumber(6)">6</button>
<button onclick="addOperator('-')">-</button>
<br>
<button onclick="addNumber(7)">7</button>
<button onclick="addNumber(8)">8</button>
<button onclick="addNumber(9)">9</button>
<button onclick="addOperator('*')">*</button>
<br>
<button onclick="addNumber(0)">0</button>
<button onclick="addOperator('/')">/</button>
<button onclick="clearResult()">清除</button>
<button onclick="calculateResult()">=</button>
<br>
</body>
</html>
```
JavaScript代码:
```javascript
var firstNumber = '';
var operator = '';
var secondNumber = '';
var result = '';
function addNumber(number) {
if (operator === '') {
firstNumber = firstNumber + number;
} else {
secondNumber = secondNumber + number;
}
document.getElementById("result").value = firstNumber + operator + secondNumber;
}
function addOperator(op) {
operator = op;
document.getElementById("result").value = firstNumber + operator;
}
function calculateResult() {
switch (operator) {
case '+':
result = parseInt(firstNumber) + parseInt(secondNumber);
break;
case '-':
result = parseInt(firstNumber) - parseInt(secondNumber);
break;
case '*':
result = parseInt(firstNumber) * parseInt(secondNumber);
break;
case '/':
result = parseInt(firstNumber) / parseInt(secondNumber);
break;
default:
break;
}
document.getElementById("result").value = result;
}
function clearResult() {
firstNumber = '';
operator = '';
secondNumber = '';
result = '';
document.getElementById("result").value = '';
}
```
这个计算器可以进行加、减、乘、除四种运算,点击“=”按钮会显示运算结果,点击“清除”按钮会清空所有输入。以上代码只是一个简单的示例,具体实现可以根据需求进行修改和扩展。
阅读全文