JavaScript中的二次方程求解器

时间:2015-10-31 17:27:03

标签: javascript

由于某种原因,当a = 1,b = 1,c = -1时,我得不到-1.6180339887499和0.61803398874989的预期结果。相反,我得到2和1.我做错了什么?

function solve(a,b,c){
    var result = (((-1*b) + Math.sqrt(Math.pow(b,2)) - (4*a*c))/(2*a));
    var result2 = (((-1*b) - Math.sqrt(Math.pow(b,2)) - (4*a*c))/(2*a));
    
    return result + "<br>" + result2;
}

document.write( solve(1,1,-1) );

3 个答案:

答案 0 :(得分:3)

您需要另一个分组:

var result = (((-1 * b) + Math.sqrt(Math.pow(b, 2)) - (4 * a * c)) / (2 * a));  // wrong
var result2 = (((-1 * b) - Math.sqrt(Math.pow(b, 2)) - (4 * a * c)) / (2 * a)); // wrong

VS

var result = (-1 * b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);      // right
var result2 = (-1 * b - Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);     // right

所有在一起:

function solve(a, b, c) {
    var result = (-1 * b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
    var result2 = (-1 * b - Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
    return result + "<br>" + result2;
}
document.write(solve(1, 1, -1));

答案 1 :(得分:0)

尝试

var a, b, c, discriminant, root1, root2, r_Part, imag_Part;

document.write(realpart ="+r_Part" and imaganary part ="+imag_Part");
discriminant = b*b-4*a*c;


if (discriminant > 0)
{
    root1 = (-b+sqrt(discriminant))/(2*a);
    root2 = (-b-sqrt(discriminant))/(2*a);

document.write(real part ="+r_Part" and imaganary part ="+imag_Part");   
}

else if (discriminant == 0)
{
    root1 = root2 = -b/(2*a);
   document.write(real part ="+r_Part" and imaganary part ="+imag_Part");
}


else
{
    r_Part = -b/(2*a);
    imag_Part = sqrt(-discriminant)/(2*a);
    document.write(real part ="+r_Part" and imaganary part ="+imag_Part");
}

答案 2 :(得分:0)

function solve(a, b, c) {
    var result = ((-1 * b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a)).toFixed(3);
    var result2 = (-1 * b - Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a).toFixed(3);
    return "{"+result + "," + result2+"}";
}
document.write(solve(1, -4, -7));