JavaScript 中的二次方程求解器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33454438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:30:35  来源:igfitidea点击:

Quadratic Equation Solver in JavaScript

javascript

提问by Stardust

For some reason, when a=1, b=1, c=-1, I am not getting the desired result of -1.6180339887499 and 0.61803398874989. Instead, I get 2 and 1. What am I doing wrong?

出于某种原因,当 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) );

回答by Nina Scholz

You need another grouping:

您需要另一个分组:

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

All together:

全部一起:

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));

回答by Hari Mohan

Try

尝试

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");
}

回答by kranthi goud

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));