后缀表达式计算

// test20.cpp : Defines the entry point for the console application.
//

#include 
"stdafx.h"
#include
<iostream>
#include
<stack>
#include
<string>
using namespace std;

class PostExp{
public:
    PostExp(
string str):evalStr(str){}
    
int evaluate();
private:
    
string evalStr;
    stack
<int> postStack;
};

/**
算式中的数字限定在0~9,因为是通过string分别读取每一个元素,如89被认定为8和9
如果操作数要扩大到9以上,则应该用数组保存算式中的每一个元素
此处为方便起见,只是为了表达后缀表达式的基本算法
*/
int PostExp::evaluate(){//后缀表达式计算
    for(string::iterator iter=evalStr.begin(); iter!=evalStr.end(); iter++){//从前至后读取
        int x,y,z;
        
if(*iter>='0' && *iter<='9')
            postStack.push(
*iter - '0');//如果读到数字,压栈
        else{//如果读到操作符,出栈两个操作数,并计算
            y=postStack.top();//y保存操作符右边的数字
            postStack.pop();
            x
=postStack.top();//x保存操作符左边的数字
            postStack.pop();
            
switch(*iter){
                    
case '+': z=x+y; break;//z保存计算结果
                    case '-' : z=x- y; break;
                    
case '*': z=x*y; break;
                    
case '/' : z=x/y;  break;
            }
            postStack.push(z);
//把计算结果作为操作数压栈
        }
    }
    
return postStack.top();
}

int main(){
    PostExp
* pe=new PostExp("352*5+-");
    cout
<<pe->evaluate();
    system(
"pause");
}

posted on 2008-10-25 18:04 deep2 阅读(2963) 评论(4)  编辑 收藏 引用 所属分类: 栈和队列

评论

# re: 后缀表达式计算 2008-10-26 03:22 陈梓瀚(vczh)

352×5--
变成
push 3
push 5
push 2
multiply
push 5
sub
sub  回复  更多评论   

# re: 后缀表达式计算 2008-10-26 14:41 金山词霸2008

一楼的怎么感觉像堆栈?  回复  更多评论   

# re: 后缀表达式计算 2008-10-26 15:32 deep2

@陈梓瀚(vczh)
352×5--
等于
push 3
push 5
push 2
multiply 5*2
push 10 (5*2的结果)
push 5
sub 10-5
push 5 (10-5的结果)
sub 3-5
push -2 (3-5的结果)

return -2   回复  更多评论   

# re: 后缀表达式计算 2009-09-27 23:00 张汤

呵呵  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2024年3月>
252627282912
3456789
10111213141516
17181920212223
24252627282930
31123456

导航

统计

常用链接

留言簿(1)

随笔分类

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜