以下是一个使用 JavaScript 实现的简单科学计算器的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>科学计算器</title>
<style>
/* 添加一些简单的样式 */
#calculator {
width: 300px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 10px;
}
input[type="button"] {
width: 50px;
height: 50px;
font-size: 20px;
margin: 5px;
}
input[type="text"] {
width: 250px;
height: 50px;
font-size: 20px;
text-align: right;
}
</style>
</head>
<body>
<div id="calculator">
<input type="text" id="result" readonly>
<br>
<!-- 按钮布局 -->
<input type="button" value="7" onclick="addToInput('7')">
<input type="button" value="8" onclick="addToInput('8')">
<input type="button" value="9" onclick="addToInput('9')">
<input type="button" value="/" onclick="addToInput('/')">
<br>
<input type="button" value="4" onclick="addToInput('4')">
<input type="button" value="5" onclick="addToInput('5')">
<input type="button" value="6" onclick="addToInput('6')">
<input type="button" value="*" onclick="addToInput('*')">
<br>
<input type="button" value="1" onclick="addToInput('1')">
<input type="button" value="2" onclick="addToInput('2')">
<input type="button" value="3" onclick="addToInput('3')">
<input type="button" value="-" onclick="addToInput('-')">
<br>
<input type="button" value="0" onclick="addToInput('0')">
<input type="button" value="." onclick="addToInput('.')">
<input type="button" value="+" onclick="addToInput('+')">
<input type="button" value="=" onclick="calculate()">
<br>
<input type="button" value="C" onclick="clearInput()">
</div>
<script>
// 处理输入的数字或操作符
function addToInput(value) {
const resultInput = document.getElementById('result');
resultInput.value += value;
}
// 清除输入
function clearInput() {
document.getElementById('result').value = '';
}
// 计算结果
function calculate() {
try {
const result = eval(document.getElementById('result').value);
document.getElementById('result').value = result;
} catch (error) {
document.getElementById('result').value = '错误';
}
}
</script>
</body>
</html>
这个示例中的计算器可以进行基本的四则运算。然而,这只是一个非常基础的版本:
可能出现的问题及解决方法:
sin(
,然后提取括号内的数值进行计算。没有搜到相关的文章