书写表达式:中缀、后缀和前缀

发布于 2024-08-08 08:25:12 字数 311 浏览 4 评论 0原文

我的任务是编写一个应用程序(不幸的是在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

枕头说它不想醒 2024-08-15 08:25:12

上面 Greg Hewgill 的评论中建议的链接包含您需要的所有信息:

如果您坚持自己编写,

  • 递归下降解析器可能是手动执行此操作的最简单方法。
  • 否则,您可以使用像 Bison 这样的工具(因为您使用的是 C 语言)。 本教程是我所见过的使用 Flex 和 Bison(或 Lex)的最佳教程/Yacc)

您还可以搜索“表达式计算器”在 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,

  • a recursive descent parser is probably the simplest way to do it by hand.
  • Otherwise you could use a tool like Bison (since you're working in C). This tutorial is the best I've seen for working with Flex and Bison (or Lex/Yacc)

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.

巨坚强 2024-08-15 08:25:12

您的问题暗示了对您的解决方案的要求:

不幸的是在C

,所以这里的一些建议可能是不允许的。尽管如此,我建议这是一个需要解决的相当复杂的问题,并且您最好尝试找到一个合适的现有库,您可以将其链接到您的 C 代码中来为您完成此操作。这可能会减少代码运行所需的时间和精力,并减少持续的维护工作。当然,您必须考虑许可,但如果“那里”没有一个好的解析/评估库可以很好地完成此工作,我会感到惊讶。

Your question hints at requirements being put on your solution:

unfortunatly on C

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文