Базовый 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))

В консоли выдает undefined. Будет ли это правильным способом решения проблемы? Если да, то как мне получить значение вместо неопределенного? Спасибо!


person Hikatchus    schedule 20.12.2020    source источник
comment
Вы ничего не возвращаете из функции, поэтому существует неявный возврат undefined. Также обратите внимание, что это не решение для квадратного выражения...ru. wikipedia.org/wiki/Quadratic_equation   -  person Jared Smith    schedule 20.12.2020
comment
Что вы пытаетесь решить? Вам даны все значения.   -  person Musa    schedule 20.12.2020
comment
Чтобы привести пример того, что пишет Джаред: перед } в методе введите return sol.   -  person Rickard Elimää    schedule 20.12.2020
comment
Возврат сработал, спасибо! И я пытался решить для y в этом уравнении   -  person Hikatchus    schedule 21.12.2020


Ответы (1)


Как и другие, вам нужно использовать ключевое слово 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>

person Pterodactylus    schedule 14.02.2021