书写表达式:中缀、后缀和前缀
我的任务是编写一个应用程序(不幸的是在 C 上),它读取中缀表示法中的表达式(带有变量、一元和二元运算符)并将其存储在内存中,然后对其求值。此外,还应检查正确性。
例如:
3*(A+B)-(-2-78)*2+(0*A)
获得所有值后,程序应该计算它。
问题是: 做到这一点的最佳方法是什么?(经过优化和验证)
选择什么符号作为树的基础?
我应该将表达式表示为树吗?如果是这样,我可以轻松优化它(只需删除返回 0 或其他值的节点)。
干杯,
My task is to write an app(unfortunatly on C) which reads expression in infix notation(with variables, unary and binary operators) and store it in memory, then evaluate it. Also, checks for correctness should be performed.
for example:
3*(A+B)-(-2-78)*2+(0*A)
After I got all values, program should calculate it.
The question is:
What is the best way to do this?(with optimization and validation)
What notation to choice as the base of tree?
Should I represent expression as tree? If so I can easily optimize it(just drop nodes which returns 0 or smth else).
Cheers,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
上面 Greg Hewgill 的评论中建议的链接包含您需要的所有信息:
如果您坚持自己编写,
您还可以搜索“表达式计算器”在 Codeproject 上 - 他们有很多关于该主题的文章。
我前段时间接触到了M4程序的表达评估器。您可以研究它的代码以了解它是如何工作的。我认为Google Codesearch 上的此链接是我看到的版本。
The link suggested in the comment by Greg Hewgill above contains all the info you'll need:
If you insist on writing your own,
You can also search for "expression evaluator" on Codeproject - they have a lot of articles on the topic.
I came across the M4 program's expression evaluator some time ago. You can study its code to see how it works. I think this link on Google Codesearch is the version I saw.
您的问题暗示了对您的解决方案的要求:
,所以这里的一些建议可能是不允许的。尽管如此,我建议这是一个需要解决的相当复杂的问题,并且您最好尝试找到一个合适的现有库,您可以将其链接到您的 C 代码中来为您完成此操作。这可能会减少代码运行所需的时间和精力,并减少持续的维护工作。当然,您必须考虑许可,但如果“那里”没有一个好的解析/评估库可以很好地完成此工作,我会感到惊讶。
Your question hints at requirements being put on your solution:
so some suggestions here might not be permissible. Nevertheless, I would suggest that this is quite a complicated problem to solve, and that you would be much better off trying to find a suitable existing library which you could link into your C code to do this for you. This would likely reduce the time and effort required to get the code working, and reduce the ongoing maintenance effort. Of course, you'd have to think about licensing, but I'd be surprised if there wasn't a good parsing/evaluation library "out there" which could do a good job of this.