Simple numerical expression solver

别说谁变了你拦得住时间么 提交于 2019-12-07 15:11:24

问题


First of all, sorry for my bad English.

For my last project on my Algorithms and Data Structures class, I need to create a simple numerical expression solver in C++. It needs to solve simple expressions like 3*12+(4-6). I managed to split the expression and separate the operators from the numbers, but I can't go any further. The trick is putting the operators on a binary tree, but I haven't managed to do that.

The program needs to use only the default C++ libs. Maybe there is some basic implementation I can build on?

Thanks in advance.


回答1:


Forget binary trees for a moment.

You need to convert the expression into reverse polish notation. During that conversion you are constructing a binary tree!

[Reverse polish notation][2]




回答2:


Look at this http://www.codeproject.com/KB/recipes/rwformulaparser.aspx I think this project will solve your problem Josemi




回答3:


You will want to convert it into reverse polish notation, the algorithm for the conversion is a little complicated, but many websites detail the exact steps. Doing multi-digit numbers will make it a little more complicated.

The most important thing you need to know is that for RPN, you will have to use a stack, not a binary tree. Once an equation is switched to RPN, you will empty it's numbers into a stack until you run into a operator, where you will then take the top two numbers from the stack and do the operation on them and put that final value back onto the stack. In the end you will be left with one number on the stack and it will be the answer to your equation.



来源:https://stackoverflow.com/questions/11162902/simple-numerical-expression-solver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!