摘要:
兩個棧:運算元棧OPND,操作符號棧OPTR
在運算式後加#
符號棧初始化時#入棧
每讀一個字元:
當它是#並且符號棧棧頂也是#時結束演算法
當它是運算元時,進數棧
當它是符號時:
1.如果符號棧頂的優先順序小於它,進符號棧
2.如果符號棧頂的優先順序大於它,出兩個數,出一個符號,計算後入數棧
3.如果與符號棧頂優先順序相等,那說明是棧頂為(,它是),(出棧
// ExpressValue.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <iostream>#include <stack>#include <map>using namespace std;int operate(int p,char opera,int q){switch(opera) {case '+': return q+p;case '-': return p-q;case '*': return p*q;case '/': return p/q; }throw "no this operation:" + opera;}bool in(char c,char array[]){int length = strlen(array);for(int i=0;i<length;i++)if(c==array[i])return true;return false;}typedef map<char,int> MAP;MAP opt;char t[][7]={{'>','>','<','<','<','>','>'},{'>','>','<','<','<','>','>'},{'>','>','>','>','<','>','>'},{'>','>','>','>','<','>','>'},{'<','<','<','<','<','=',0},{'>','>','>','>',0,'>','>'},{'<','<','<','<','<',0,'='} };char precede(char a,char b){return t[opt[a]][opt[b]];}int main(int argc, char* argv[]){freopen("i://t.txt","r",stdin);char op[]={'+','-','*','/','(',')','#',0};opt.insert(MAP::value_type('+',0));opt.insert(MAP::value_type('-',1));opt.insert(MAP::value_type('*',2));opt.insert(MAP::value_type('/',3));opt.insert(MAP::value_type('(',4));opt.insert(MAP::value_type(')',5));opt.insert(MAP::value_type('#',6));while(1){stack<char> optr,opnd;optr.push('#');char c = getchar();if(c=='e')return 0;while(!(c=='#'&&optr.top()=='#')){if(!in(c,op)){opnd.push(c-'0');c = getchar();}else{switch(precede(optr.top(),c)){case '<':optr.push(c);c = getchar();break;case '=':optr.pop();c = getchar();break;case '>':int a = opnd.top();opnd.pop();int b = opnd.top();opnd.pop();char ope = optr.top();optr.pop();opnd.push(operate(b,ope,a));//printf("[%d %c %d = %d]",b,ope,a,operate(b,ope,a));break;}}}printf("%d\n",opnd.top());}return 0;}
測試資料:
1+1+2#2*3+5#1#4/2+6#6*2*(2+5)#6*2*(2+5)/7#1+8/(1+1)#2*(4+4)/8+8-2#8*9/3-8#end