防爆pression评价评价、pression

2023-09-11 04:57:49 作者:人丑嘴贱脾气大

我在做一个前pression估值程序,就像这个。我的问题是,我无法弄清楚如何处理操作precedences。我递归用来寻找最里面的几个括号,并发现时,解决了前pression在他们里面,像这样的:

I'm doing an expression valuation program, just like this. My problem is that I can't figure out how to handle operation precedences. I used recursion to find the innermost couple of parenthesis and, when found, solve the expression inside them, like this:

Evaluate("2 + (3 * 5)")

将重新调用本身是这样的:

will re-call itself this way:

Evaluate("3 * 5")

现在,因为没有括号,它计算的结果,并调用自身另一个时间:

now, since there aren't parenthesis, it calculates the result and calls itself another time:

Evaluate("2 + 15")

好了,返回值是17,符合市场预期。但是,如果我叫评估(2 + 3 * 5)的结果是:

Evaluate("2 + 3 * 5")
Evaluate("5 * 5")

这显然是错误的。照片 基本上我解决操作左到右。我该如何选择,必须首先进行的操作?我想添加一对括号周围的每一个操作的,但它并没有看起来那么好。 所以,我需要首先分析整个EX pressionØ有另一种方式?

Which is clearly wrong. Basically I'm solving operations from left to right. How can I chose the operations that must be performed first? I was thinking to add a couple of parenthesis surrounding every operation, but it doesn't look so good. So, do I need to parse the whole expression first o there's another way?

推荐答案

搜索您的highest- precedence运营商,这样做第一,然后继续前进。所以,如果你只有+和*,​​搜索的情况下,*并与AAAA * BBBB值替换子AAAA * BBBB。一旦没有这样的情况依然存在,工作+。

Search for your highest-precedence operator and do that first, then move on. So if you have only + and *, search for instances of * and replace the substring aaaa * bbbb with the value of aaaa * bbbb. Once no such instances remain, work on +.

如果在给定的操作符的事项顺序(例如,如果包括^),你必须决定从哪里开始与这些运营商。

If order within a given operator matters (for example, if you include ^) you'll have to decide where to start with those operators.