vscode做简易计算器代码
时间: 2024-09-13 07:09:57 浏览: 128
VSCode(Visual Studio Code)是一个轻量但功能强大的源代码编辑器,它支持多种编程语言的开发。要用VSCode编写一个简易计算器的代码,可以使用多种编程语言,例如JavaScript、Python等。这里我将提供一个简单的JavaScript示例代码,可以在网页中运行这个计算器。
以下是一个简易计算器的HTML和JavaScript代码示例:
```html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>简易计算器</title>
</head>
<body>
<input type="text" id="display" disabled>
<button onclick="clearDisplay()">C</button>
<button onclick="inputValue('1')">1</button>
<button onclick="inputValue('2')">2</button>
<button onclick="inputValue('3')">3</button>
<button onclick="setOperation('+')">+</button>
<button onclick="inputValue('4')">4</button>
<button onclick="inputValue('5')">5</button>
<button onclick="inputValue('6')">6</button>
<button onclick="setOperation('-')">-</button>
<button onclick="inputValue('7')">7</button>
<button onclick="inputValue('8')">8</button>
<button onclick="inputValue('9')">9</button>
<button onclick="setOperation('*')">*</button>
<button onclick="inputValue('0')">0</button>
<button onclick="calculate()">=</button>
<button onclick="setOperation('/')">/</button>
<script>
let display = document.getElementById('display');
let currentInput = '';
let operation = null;
let firstNumber = true;
function inputValue(val) {
if (display.value === 'Error') {
clearDisplay();
}
currentInput += val;
display.value = currentInput;
}
function setOperation(op) {
if (display.value === 'Error') {
clearDisplay();
}
if (currentInput !== '') {
operation = op;
firstNumber = false;
}
}
function calculate() {
if (operation && !firstNumber) {
let secondNumber = parseFloat(currentInput);
let result;
switch (operation) {
case '+':
result = performOperation('+', secondNumber);
break;
case '-':
result = performOperation('-', secondNumber);
break;
case '*':
result = performOperation('*', secondNumber);
break;
case '/':
if (secondNumber === 0) {
display.value = 'Error';
return;
}
result = performOperation('/', secondNumber);
break;
}
display.value = result;
operation = null;
firstNumber = true;
currentInput = result.toString();
}
}
function performOperation(op, secondNumber) {
let firstNumberValue = parseFloat(display.value);
switch (op) {
case '+':
return firstNumberValue + secondNumber;
case '-':
return firstNumberValue - secondNumber;
case '*':
return firstNumberValue * secondNumber;
case '/':
return firstNumberValue / secondNumber;
}
}
function clearDisplay() {
display.value = '';
currentInput = '';
operation = null;
firstNumber = true;
}
</script>
</body>
</html>
```
这个简易计算器具备了基本的加、减、乘、除功能。用户点击按钮输入数字或者选择操作符,然后点击等号按钮进行计算。
阅读全文