应用java script制作一个计算器,可以对整数和小数进行加减乘除运算
时间: 2024-01-14 19:05:19 浏览: 88
jisuanqi.zip_小数计算器_小数运算_计算器 小数_计算器+小数_计算器小数
好的,以下是一个简单的实现:
HTML代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>计算器</title>
<meta charset="utf-8">
<script src="calculator.js"></script>
</head>
<body>
<h1>计算器</h1>
<input type="text" id="result" readonly>
<br>
<button onclick="clearResult()">清除</button>
<button onclick="calculate('/')">÷</button>
<br>
<button onclick="addNumber(7)">7</button>
<button onclick="addNumber(8)">8</button>
<button onclick="addNumber(9)">9</button>
<button onclick="calculate('*')">x</button>
<br>
<button onclick="addNumber(4)">4</button>
<button onclick="addNumber(5)">5</button>
<button onclick="addNumber(6)">6</button>
<button onclick="calculate('-')">-</button>
<br>
<button onclick="addNumber(1)">1</button>
<button onclick="addNumber(2)">2</button>
<button onclick="addNumber(3)">3</button>
<button onclick="calculate('+')">+</button>
<br>
<button onclick="addNumber(0)">0</button>
<button onclick="addNumber('.')">.</button>
<button onclick="calculate('=')">=</button>
</body>
</html>
```
JavaScript代码:
```javascript
let firstNumber = null;
let secondNumber = null;
let operator = null;
let result = null;
function addNumber(number) {
let currentResult = document.getElementById("result").value;
if (currentResult === "0") {
currentResult = "";
}
if (number === "." && currentResult.includes(".")) {
return;
}
document.getElementById("result").value = currentResult + number;
}
function clearResult() {
document.getElementById("result").value = "0";
firstNumber = null;
secondNumber = null;
operator = null;
result = null;
}
function calculate(newOperator) {
let currentResult = parseFloat(document.getElementById("result").value);
if (operator === null) {
firstNumber = currentResult;
operator = newOperator;
result = firstNumber;
} else {
secondNumber = currentResult;
switch (operator) {
case "+":
result = firstNumber + secondNumber;
break;
case "-":
result = firstNumber - secondNumber;
break;
case "*":
result = firstNumber * secondNumber;
break;
case "/":
result = firstNumber / secondNumber;
break;
default:
break;
}
firstNumber = result;
operator = newOperator;
}
document.getElementById("result").value = "0";
if (newOperator === "=") {
document.getElementById("result").value = result;
firstNumber = null;
secondNumber = null;
operator = null;
result = null;
}
}
```
这个计算器可以对整数和小数进行加减乘除运算,并且可以连续进行多次运算。
阅读全文