// 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;
};
/**
算式中的數(shù)字限定在0~9,因?yàn)槭峭ㄟ^(guò)string分別讀取每一個(gè)元素,如89被認(rèn)定為8和9
如果操作數(shù)要擴(kuò)大到9以上,則應(yīng)該用數(shù)組保存算式中的每一個(gè)元素
此處為方便起見(jiàn),只是為了表達(dá)后綴表達(dá)式的基本算法
*/
int PostExp::evaluate(){//后綴表達(dá)式計(jì)算
for(string::iterator iter=evalStr.begin(); iter!=evalStr.end(); iter++){//從前至后讀取
int x,y,z;
if(*iter>='0' && *iter<='9')
postStack.push(*iter - '0');//如果讀到數(shù)字,壓棧
else{//如果讀到操作符,出棧兩個(gè)操作數(shù),并計(jì)算
y=postStack.top();//y保存操作符右邊的數(shù)字
postStack.pop();
x=postStack.top();//x保存操作符左邊的數(shù)字
postStack.pop();
switch(*iter){
case '+': z=x+y; break;//z保存計(jì)算結(jié)果
case '-' : z=x- y; break;
case '*': z=x*y; break;
case '/' : z=x/y; break;
}
postStack.push(z);//把計(jì)算結(jié)果作為操作數(shù)壓棧
}
}
return postStack.top();
}
int main(){
PostExp* pe=new PostExp("352*5+-");
cout<<pe->evaluate();
system("pause");
}