电脑技术学习

自动计算二次函数的根值

dn001

<!-- 把下面代码加到<body>区域中 -->
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
<!--
function findRoots() {
var ff = document.forms[
"quad"];
var a = ff.elements[
"a"].value;
var b = ff.elements[
"b"].value;
var c = ff.elements[
"c"].value;
if(a.length == 0 || a == "0") {
alert("The co-efficient of x^2 must be a non-zero number.");
return;
}
var addOf = -1*b;
var rootOf = b*b - 4*a*c;
var denomOf = 2*a;
ff.elements[
"be"].value = addOf;
ff.elements[
"root"].value = rootOf;
ff.elements[
"denom"].value = denomOf;
var firstDivide = addOf / denomOf;
if(rootOf == 0) {
ff.elements[
"x1"].value = firstDivide;
ff.elements[
"x2"].value = "";
} else if(rootOf < 0) {

rootOf *= -1;
rootOf = Math.sqrt(rootOf);
rootOf /= denomOf;
ff.elements[
"x1"].value = firstDivide + " + i" + rootOf;
ff.elements[
"x2"].value = firstDivide + " - i" + rootOf;
} else if(rootOf > 0) {
rootOf = Math.sqrt(rootOf);
rootOf /= denomOf;
ff.elements[
"x1"].value = (firstDivide + rootOf);
ff.elements[
"x2"].value = (firstDivide - rootOf);
}
}
//-->
//; End -->
</script>
<form name="quad" onsubmit="return false;">
<p>请输入相关数据
</p><p>
y = <input name="a" value="6" class="num" size=2>x<sup>2</sup> +
<input name="b" value="12" class="num" size=2>x +
<input name="c" value="18" class="num" size=2>
</p><p>
<input type="button" value="计算" onclick="findRoots();">
</p>
<p>
<table cellpadding=0 cellspacing=0 border=0>
<tr>
<td rowspan=3 align="right">
x<sub>1</sub>, x<sub>2</sub> =
</td>
<td align="center">
<input name="be" class="num" size=2> + root(<input name="root" class="num" size=3>)
</td>
<td rowspan=3>
=
</td>
<td rowspan=3 align="left">
<input name="x1" class="num" size="25"><br><input name="x2" class="num" size="25">
</td>
</tr>
<tr>
<td>
<hr width="100%" size=1>
</td>
</tr>
<tr>
<td align="center">
<input name="denom" class="num" size=3>
</td></tr></table></p>
</form>