演算法運算式求值

來源:互聯網
上載者:User

摘要:

兩個棧:運算元棧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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.