-1

大家好。我想制作一个可以求解二次方程的程序,例如:0 = ax^2+bx+c。我可以使用变量 a、b、c 来解决它。问题是您必须手动选择 a、b 和 c。有没有办法从这样的方程中获取变量?0 = 5x^2 + 4x + 3 这里我们会得到 a = 5 b = 4 c = 3

顺便说一句,我正在用javascript做。我希望你能帮帮我

4

2 回答 2

0

This should be more than enough to get you going; some assembly required.

Do you know if the Y value will always be on the left? Whether you'll ever see the form Ax^2 + Bx + C = 0 may add a step or two; I'll assume Y will always be on the left.

  1. I would start by removing all white-space from the string.
    • quadratic = quadratic.replace(/ /g,'');
  2. Then split the string by = and work with the right side.
  3. Extract your variables (while preserving negatives).

    • var A = quad.match(/([-]?\d+)(?=[a-zA-Z]\^2)/);
      quadratic = quadratic.match(/-?\d+[a-zA-Z]\^2/,'');
      var B = quadratic.match(/-?\d+(?![a-zA-Z]\^)(?=[a-zA-Z])/); quadratic = quadratic.replace(/-?\d+[a-zA-Z]/,'');
      var C = quadratic.match(/-?\d+/);
  4. Plug that into (-B ±√(B2 - 4AC))/2a and test the results

    • You obviously have to do two separate functions as there is no ± operator.
    • Hint: squared is Math.pow(x,2) and square root is Math.pow(x,.5) or Math.sqrt(x).
    • Remember that if the discriminate is >0 there are two real solutions, =0 there is one real solution, or <0 there are no real solutions (but two complex solutions).
于 2013-10-26T23:21:36.447 回答
0

我认为拆分方法在这里可以为您工作:http: //www.w3schools.com/jsref/jsref_split.asp 首先将字符串拆分为“+”,然后将每个字符串拆分为“x”,然后获取第一个元素三个数组。

这假定添加的每个函数都具有相同的格式。您必须将所有减号变成加号(通过使乘数为负),或者检查以拆分减号。

于 2013-10-26T20:10:33.970 回答