非常新的程序员,尝试用 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))
在控制台中,输出“未定义”。这是解决问题的正确方法吗?如果是这样,我将如何获得一个值而不是未定义的?谢谢!
就像其他人所说,您需要使用“return”关键字来返回值。你想找到方程的零点吗?如果是这样,这里是数值解:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script src="https://www.desmos.com/api/v1.4/calculator.js?apiKey=dcb31709b452b1cf9dc26972add0fda6"></script>
</head>
<body>
<h3>Quadratic Function</h3>
<p>This is an example of the solution of the quadratic function using <a href="https://github.com/Pterodactylus/ceres.js">Ceres.js</a></p>
<pre><code id="quadratic_demo_code" class="language-js"></code></pre>
<div id="calculator" style="width: 600px; height: 400px;"></div>
<script>
var elt = document.getElementById('calculator');
var calculator = Desmos.GraphingCalculator(elt);
calculator.setExpression({ id: 'exp1', latex: 'x+10*y-20 = 0' });
calculator.setExpression({ id: 'exp2', latex: "\\sqrt{5}*x-y^2 = 0" });
</script>
<p><textarea id="quadratic_demo" rows="40" cols="110"></textarea></p>
<script id="quadratic_demo_code_source">
async function ceresSolveQuadratic() {
const {Ceres} = await import('https://cdn.jsdelivr.net/gh/Pterodactylus/Ceres.js@latest/dist/ceres.min.js');
var fn1 = function f1(x){
return (x[0]+10*x[1]-20); //this equation is of the for f1(x) = 0
}
var fn2 = function f2(x){
return (Math.sqrt(5)*x[0]-Math.pow(x[1], 2)); //this equation is of the for f2(x) = 0
}
let solver = new Ceres()
solver.addFunction(fn1) //Add the first equation to the solver.
solver.addFunction(fn2) //Add the second equation to the solver.
//solver.addCallback(c1) //Add the callback to the solver.
//solver.addLowerbound(0,1.6) //Add a lower bound to the x[0] variable
//solver.addUpperbound(1,1.7) //Add a upper bound to the x[1] variable
var x_guess = [1,2] //Guess the initial values of the solution.
let s = await solver.solve(x_guess) //Solve the equation
var x = s.x //assign the calculated solution array to the variable x
document.getElementById("quadratic_demo").value = s.report //Print solver report
solver.remove() //required to free the memory in C++
}
ceresSolveQuadratic()
</script>
</body>
</html>