HTML 是一种标记语言,用于创建网页的结构和内容。它本身并不能实现计算功能,因为计算通常涉及到处理数据和执行算法,这是 HTML 无法做到的。然而,你可以使用 HTML 来构建一个简单的计算器界面,并通过 JavaScript 或其他编程语言来实现计算功能。
<!DOCTYPE html> |
<html> |
<head> |
<title>简单计算器</title> |
<style> |
.calculator { |
width: 200px; |
height: 250px; |
border: 1px solid #ccc; |
padding: 10px; |
} |
.calculator button { |
width: 40%; |
height: 40px; |
margin: 5px; |
padding: 5px; |
border: none; |
background-color: #ccc; |
color: #fff; |
font-size: 16px; |
cursor: pointer; |
} |
</style> |
</head> |
<body> |
<div class="calculator"> |
<button onclick="clearDisplay()">C</button> |
<input type="text" id="display" readonly> |
<br> |
<button onclick="appendDigit(7)">7</button> |
<button onclick="appendDigit(8)">8</button> |
<button onclick="appendDigit(9)">9</button> |
<button onclick="calculate(2)">/</button> |
<br> |
<button onclick="appendDigit(4)">4</button> |
<button onclick="appendDigit(5)">5</button> |
<button onclick="appendDigit(6)">6</button> |
<button onclick="calculate(3)">*</button> |
<br> |
<button onclick="appendDigit(1)">1</button> |
<button onclick="appendDigit(2)">2</button> |
<button onclick="appendDigit(3)">3</button> |
<button onclick="calculate(1)">+</button> |
<br> |
<button onclick="calculate(0)">=</br></button> |
<button onclick="appendDigit(0)">0</button> |
<button onclick="calculate(0)">-</button> |
</div> |
<script> |
var display = document.getElementById('display'); |
var result = ''; |
var operator = ''; |
var num1 = 0; |
var num2 = 0; |
var operatorStack = []; |
var resultStack = []; |
function appendDigit(digit) { |
display.value += digit; |
if (operator !== '') { // 如果当前有运算符,将数字加到 num2 上,并清空 num1 和 num2 用于下一位数字输入。 |
num2 = Number(display.value); // 将数字转换为数值类型并存储到 num2 中。 |
num1 = 0; // 清空 num1。 |
display.value = ''; // 清空显示框。 |
} else { // 如果当前没有运算符,将数字加到 num1 上。 |
num1 = Number(display.value); // 将数字转换为数值类型并存储到 num1 中。 |
display.value = ''; // 清空显示框。 |
} |
} |
function calculate(operator) { // 计算函数,根据运算符进行相应的计算。 |
num2 = num1; // 将 num1 的值赋给 num2。 |
num1 = eval(result); // 将结果加到 num1 上。 |
operatorStack.push(operator); // 将运算符压入运算符栈中。 |
resultStack.push(num1); // 将结果加到结果栈中。 |
result = display.value; // 将显示框的值赋给结果变量。清空显示框,等待下一次输入。 |