javascript - 基本的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))
在控制台中,它输出“未定义”。这是解决问题的正确方法吗?如果是这样,我将如何获得一个值而不是未定义?谢谢!
解决方案
就像其他人说的那样,您需要使用“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>
推荐阅读
- python-3.x - 在 python 循环中引用文件名
- android - 如何在外部触摸时将动画添加到警报对话框中
- html - 如何使用 Puppeteer 在没有 href 链接的情况下获取标签内的文本
- java - Lombok 的 lombok.copyableAnnotations 不适用于 Jackson 注释
- r - 使用不同长度的列名作为循环列表
- android - 有没有办法使用 android.R.layout. 访问系统键盘布局文件?
- java - Netty 不能在 vps 上启动
- python - 有没有办法输入递归数据类?
- react-native - 反应本机模块解析失败:所有node_modules文件中的意外令牌
- javascript - 删除和替换连续字符