问题描述
我目前正在编写一个可解决方程式的PHP程序.我已将输入方程式分成一个数组,以便数组中的每一行都包含一个项. (因此[0] ="+ 5x",[1] ="=",[2] ="-5",[3] ="+10".这只是一个基本等式.脚本还对以下内容进行了划分是()中的子数组,例如2x +(5-3x)= 3(x + 1)[0] ="+ 2 * x",[1] = array([0] ="+5" ....
I'm currently making a PHP-program that solves equations. I've divided the input equation into an array so that each line in the array contains one term. (So. [0] = "+5x", [1] = "=", [2] = "-5", [3] = "+10". This is just a basic equation. The script also divides what is in () into sub-arrays. So for example 2x+(5-3x)=3(x+1) [0] = "+2*x", [1] = array([0] = "+5"....
但是,我发现表达式树非常适合在此方程式求解器中使用.我已经搜索了整个互联网来学习它,但是找不到任何用PHP解释它的网站(我知道PHP OOP.).例如,在C语言中有很多页面对其进行了解释,但是据我所知,PHP毫无帮助,因为我不理解示例代码.
However, I discovered expression trees that is the perfect thing to use in this equation-solver. I've searched the whole internet to learn it, but I can't find any websites that explain it in PHP (I know PHP OOP.). There are lots of pages explaining them in for example C, but as I only know PHP, that is of no help, because I don't understand the example code.
任何人都可以在PHP中解释有关表达式树的所有内容以及一些实际的示例代码吗?
Can anyone here explain everything about expression trees in PHP and some practical example code?
推荐答案
这是算法描述.您可以在PHP中实现此功能.我认为没有人已经在PHP中实现了这一点(并将其作为开源分发)
Here is the algorithm described. you can implement this in PHP. I don't think anyone already implemented this in PHP (and distribute it as open source)
一个例子是:
2*x+3*5-(6+9) = 0
位置:
-
*
=优先级2 -
+
=优先级1 -
(
=将标志的优先级提高10 -
+
(秒+)=优先级11 -
)
=会将标志的优先级降低10 -
=
=在这种情况下,它表明还有另一个表达式(0)
*
= priority 2+
= priority 1(
= will increase priority of signs by 10+
(second +) = priority 11)
= will decrease priority of signs by 10=
= in this case it is showing that there is another expression (0)
最高优先级是最重要的-您首先需要做的
The highest priority is the most important - the one you need to do first
使用这些规则,您可以创建一个表达式树...
Using these rules you can create an expression tree...
...您必须先创建表达式然后进行解释的一种方式是:
So.. a way in which you have to create the expression and then interpret is:
2 x * 3 5 * + 6 9 + -
解释:
-
2 * x | (1)
-
3 * 5 | (2)
-
(1) + (2) | (3)
-
6 + 9 | (4)
-
(3) - (4) = final
2 * x | (1)
3 * 5 | (2)
(1) + (2) | (3)
6 + 9 | (4)
(3) - (4) = final
我不记得是怎么写树的,我在计算机科学专业的课程中是这样做的,但是它是这样的:
I don't remember exactly how to write a tree I did this to a course in Computer Science but it was something like this:
-
/ \
E (E)
| +
+ / \
/ \ 6 9
E E
| |
* *
/ \ / \
T E T E
| | | |
2 T 3 T
| |
x 5
现在,您必须为此创建自己的解释器.您可以使用解释器模式: PHP解释器
Now you have to create your own interpreter for this. You can use the interpreter pattern: PHP Interpreter
这篇关于如何在PHP中使用表达式树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!