如何编写一个遵循优先规则的计算器程序? [英] how to write a calculator program which obey precedence rules?

查看:105
本文介绍了如何编写一个遵循优先规则的计算器程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我正在一个需要帮助的C ++项目中.
在此项目中,程序应获得一个短语,例如:
7 + 2 * 3 + 4/2
并计算出来.困难的部分是它应遵守优先规则.
并且如果它可以支持幂和括号;我会好一些,但那是必要的.
谁能给我一个主意或提示?
问候,

Hi,
I am working on a C++ project that I need help for it.
In this project the program should get a phrase, for example:
7+2*3+4/2
and calculate it. The hard part is that it should obey precedence rules.
And If it can support power and parentheses; I will be better but it is nit nessecary.
Could anyone give me an idea or a hint?
Regards,

推荐答案

如果您想支持优先级,则需要获取整个字符串并进行解析,您不能随便做不会知道优先顺序.因此,您要编写的是一个字符串解析引擎,该引擎可以确定优先级的顺序,在应用+和-之前先搜索*和/.
If you want to support precedence, you need to take the entire string and parse it, you can''t do it as you go, as you won''t know the precedence. So, what you want to write is a string parsing engine that works out the order of precedence as it goes, searching for * and / before applying + and -.


您可以编写自己的字符串expression parser(例如,参见[ ^ ]或您可以使用工具,例如flex [ ^ ] + bison [ ^ ]或ANTLR [ ^ ])并使其对您的表达式进行评估.
You may write your own expression parser (see, for instance [^] or you may use a tool, such flex [^]+bison[^] or ANTLR [^], for this task.
You may even embed a script language (like, for instance Lua [^]) in your application and make it evaluate the expression for you.


您必须为其编写一个表达式解析器,以实现堆栈操作.
you have to write an expression parser for it, implementing stack operation.


这篇关于如何编写一个遵循优先规则的计算器程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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