js计算一元二次方程,并且在网页中显示输入和输出
时间: 2023-05-30 10:07:39 浏览: 85
JS实现简单的二元方程计算器功能示例
以下是一元二次方程的计算器:
<!DOCTYPE html>
<html>
<head>
<title>一元二次方程计算器</title>
</head>
<body>
<h1>一元二次方程计算器</h1>
<form>
<p>请输入一元二次方程的三个系数:</p>
<input type="number" id="a" placeholder="a">
<label for="a">x² + </label>
<input type="number" id="b" placeholder="b">
<label for="b">x + </label>
<input type="number" id="c" placeholder="c">
<label for="c"> = 0</label>
<br><br>
<button type="button" onclick="calculate()">计算</button>
</form>
<br>
<p id="result"></p>
<script>
function calculate() {
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var c = document.getElementById("c").value;
var delta = b * b - 4 * a * c;
if (a == 0) {
document.getElementById("result").innerHTML = "这不是一元二次方程!";
} else if (delta < 0) {
document.getElementById("result").innerHTML = "该方程无实数解!";
} else if (delta == 0) {
var x = -b / (2 * a);
document.getElementById("result").innerHTML = "该方程有唯一解 x = " + x;
} else {
var x1 = (-b + Math.sqrt(delta)) / (2 * a);
var x2 = (-b - Math.sqrt(delta)) / (2 * a);
document.getElementById("result").innerHTML = "该方程有两个解 x1 = " + x1 + ",x2 = " + x2;
}
}
</script>
</body>
</html>
阅读全文