首页 > 解决方案 > 基本的javascript求解二次方程

问题描述

非常新的程序员,试图用javascript制作一个二次方程求解器。

//QuadSolver, a b c as in classic ax^2 + bx + c format
function quadsolve(x, a, b, c) {
  var sol = (
    ((a * (x * x)) + (b * x)) + c
    )
}
//Test
console.log(quadsolve(1, 1, 1, 0))

在控制台中,它输出“未定义”。这是解决问题的正确方法吗?如果是这样,我将如何获得一个值而不是未定义?谢谢!

标签: javascriptsolverquadratic

解决方案


就像其他人说的那样,您需要使用“return”关键字来返回一个值。你想找到方程的零点吗?如果是这样,这里是数字解决方案:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script id="MathJax-script" async
        src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js">
</script>
</head>
<body>

<h2>Quadratic Equation</h2>
<p>This is an example of the numerical solution of a quadratic equation using <a href="https://github.com/Pterodactylus/Ceres.js">Ceres.js</a></p>
<p>
Problem Statment: find x when \(f(x)=0\)
\[f(x) = a*x^2+b*x+c\]

</p>

<textarea id="demo" rows="40" cols="170">
</textarea>

<script type="module">
    import {Ceres} from 'https://cdn.jsdelivr.net/gh/Pterodactylus/Ceres.js@master/Ceres-v1.5.3.js'

    var fn1 = function(x){
    let a = 1
    let b = -1
    let c = 1
        return a*x[0]*x[0]+b*x[0]+c //this equation is of the form f(x) = 0 
    }
    
    let solver = new Ceres()
    solver.add_function(fn1) //Add the first equation to the solver.
    
    solver.promise.then(function(result) { 
        var x_guess = [1] //Guess the initial values of the solution.
        var s = solver.solve(x_guess) //Solve the equation
        var x = s.x //assign the calculated solution array to the variable x
        document.getElementById("demo").value = "The solution is x="+x+"\n\n"+s.report //Print solver report
        solver.remove() //required to free the memory in C++
    })
</script>
</body>
</html>


推荐阅读