等式的Javascript代码

时间:2013-04-17 19:58:20

标签: javascript equation

我搜索了一个解决方案,但我仍然遇到同样的问题。我有一个javascript代码,解决了二度方程。这里有我的代码::

var x1 = document.getElementById('x1').value;
var x2 = document.getElementById('x2').value;
var x3 = document.getElementById('x3').value;
var x4 = document.getElementById('x4').value;
var x5 = document.getElementById('x5').value;


var discriminant = (x2*x2)-(4*(x1*x3));
if (discriminant > -1){
var x1 = (-x2+Math.sqrt(discriminant))/(2*x1); 
var x2 = (-x2-Math.sqrt(discriminant))/(2*x1);
document.getElementById('totx1').value = x1;
document.getElementById('totx2').value = x2;
var temp1 = (x5*x1)+1*x4;
document.getElementById('toty1').value = temp1;
var temp2 = (x5*x2)+1*x4;
document.getElementById('toty2').value = temp2;}

由于某些原因,x1是正确的,但x2给出了错误的结果。谁能帮助我?在这里您可以看到输入示例:

2x ^ 2 + 2x - 40 = 0 | y = x4 + x5

正确的解是[x1 = 4 || y1 = 5]和[x2 = -4 || y2 = -5]但我得到[x1 = 4 || y1 = 5]和[x2 = -10 || y2 = -9]

1 个答案:

答案 0 :(得分:1)

使用parseFloat:

var x1 = parseFloat(document.getElementById('x1').value);

并为输入和输出使用不同的变量名称:重用x1这一事实会导致错误:

var x1 = (-x2+Math.sqrt(discriminant))/(2*x1); 
var x2 = (-x2-Math.sqrt(discriminant))/(2*x1);