如何分析涉及括号数学EX pressions [英] How to parse mathematical expressions involving parentheses

查看:141
本文介绍了如何分析涉及括号数学EX pressions的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是不是学校里的功课或什么,但我知道这是一个主要的学术问题。但是,我一直在努力做的是分析的数学文本,并想出了一个答案。

This isn't a school assignment or anything, but I realize it's a mostly academic question. But, what I've been struggling to do is parse 'math' text and come up with an answer.

例如 - 我可以找出如何解析5 + 5或3·5' - 但是当我尝试正确连锁经营在一起我失败

For Example - I can figure out how to parse '5 + 5' or '3 * 5' - but I fail when I try to correctly chain operations together.

(5 + 5)* 3

(5 + 5) * 3

它大多只是缠着我,我不能弄明白。如果任何人都可以在一个方向指向我,我真的AP preciate吧。

It's mostly just bugging me that I can't figure it out. If anyone can point me in a direction, I'd really appreciate it.

修改 感谢所有的快速响应。我很抱歉,我没有做解释工作做得更好。

EDIT Thanks for all of the quick responses. I'm sorry I didn't do a better job of explaining.

首先 - 我没有使用常规的前pressions。我也知道已经有,将采取,作为一个字符串,数学EX pression并返回正确的值可用的库。所以,我主要是看这个,因为,可悲的是,我不明白。

First - I'm not using regular expressions. I also know there are already libraries available that will take, as a string, a mathematical expression and return the correct value. So, I'm mostly looking at this because, sadly, I don't "get it".

二 - 我试着做(也许是错误的),但我期待着'('和')',并第一次评估最深的项目。在简单的例子,这个工作;但我的code不是pretty的,更复杂的东西崩溃。当我'计算'的最低水平,我修改字符串。

Second - What I've tried doing (is probably misguided) but I was counting '(' and ')' and evaluating the deepest items first. In simple examples, this worked; but my code is not pretty and more complicated stuff crashes. When I 'calculated' the lowest level, I was modifying the string.

所以... (5 + 5)* 3

So... (5 + 5) * 3

会变成 10 * 3

Would turn into 10 * 3

这会再评估为 30

但它只是觉得错误的。

我希望帮助澄清的事情。我肯定会看看提供的链接。

I hope that helps clarify things. I'll certainly check out the links provided.

推荐答案

树龄一个简单的图形应用程序工作时以前,我用的这个算法(这是比较容易理解和简单的数学EX pressions这样的伟大工程),以第一次打开EX pression成的 RPN ,然后计算出结果。 RPN是很好,速度很快针对不同的变量值来执行。

Ages ago when working on a simple graphing app, I used this algorithm (which is reasonably easy to understand and works great for simple math expressions like these) to first turn the expression into RPN and then calculated the result. RPN was nice and fast to execute for different variable values.

当然,语言的解析是一个非常广泛的话题,也有绕了(和pre制造工具太)许多其他方面

Of course, language parsing is a very wide topic and there are many other ways of going about it (and pre-made tools for it too)

这篇关于如何分析涉及括号数学EX pressions的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆