我正在尝试制作一个使用JavaScript解决二次方程式的程序。这是我的代码:
"use strict";
function calculation()
{
var a, b , c , delta , x1, x2;
a = Number(document.getElementById("a").value);
b = Number(document.getElementById("b").value);
c = Number(document.getElementById("c").value);
delta = Math.pow(b,2)-4*a*c;
x1 = (-1*b + Math.sqrt(delta))/(2*a);
x2 = (-1*b - Math.sqrt(delta))/(2*a);
document.getElementById("result").value= x1;
document.getElementById("result1").value= x2;
if(delta<0)
{ document.getElementById("result").value= "No real solution"
document.getElementById("result1").value= "No real solution"
}
if(delta==0)
{var result2 = b*(-1)/(2*a)
document.getElementById("result").value = result2
document.getElementById("result1").value = "No real solution"
}
if(delta>0)
{
document.getElementById("result").value = result
document.getElementById("result1").value = result1
}
if(a==0)
{document.getElementById("message").innerHTML="This is not a quadratic equation"
document.getElementById("result").value= "No real solution"
document.getElementById("result1").value= "No real solution"
}
else {
document.getElementById("result").value = result
document.getElementById("result1").value = result1
}
}
但是,它仅输出[object HTMLInputElement]
。为什么会这样?
答案 0 :(得分:0)
如果没有HTML部分,很难说出来,但是似乎您从未启动result
和result1
变量。
答案 1 :(得分:0)
"use strict";
function calculation()
{
var a, b , c , delta , x1, x2;
a = Number(document.getElementById("a").value);
b = Number(document.getElementById("b").value);
c = Number(document.getElementById("c").value);
delta = Math.pow(b,2)-4*a*c;
x1 = (-1*b + Math.sqrt(delta))/(2*a);
x2 = (-1*b - Math.sqrt(delta))/(2*a);
// YOU ARE SETTING THE RESULT VALUES HERE ASSUMING THEY ARE GOOD
// document.getElementById("result").value= x1;
// document.getElementById("result1").value= x2;
if(delta<0)
{ document.getElementById("result").value= "No real solution"
document.getElementById("result1").value= "No real solution"
}
if(delta==0)
{var result2 = b*(-1)/(2*a)
document.getElementById("result").value = result2
document.getElementById("result1").value = "No real solution"
}
if(delta>0)
{
document.getElementById("result").value = x1; // HERE TOO USE VARIABLE NOT OBJECT
document.getElementById("result1").value = x2; // HERE TOO USE VARIABLE NOT OBJECT
}
if(a==0)
{document.getElementById("message").innerHTML="This is not a quadratic equation"
document.getElementById("result").value= "No real solution";
document.getElementById("result1").value= "No real solution";
}
// THESE ARE THE LINES SAYING .value = an html object.
// else {
// document.getElementById("result").value = result
// document.getElementById("result1").value = result1
// }
// RECOMMEND ONLY SETTING IF YOU DETERMINE VALUES ARE USEFUL AND SETTING .value = variable
else {
document.getElementById("result").value = x1;
document.getElementById("result1").value = x2;
}
}