資料結構--算數運算式求值

來源:互聯網
上載者:User

標籤:資料結構   number   cat   ios   算數   end   byte   tran   cpp   

#include "pch.h"#include <windows.h>#include <iostream>#include <stack>using std::stack;using std::cin;using std::cout;using std::endl;using std::cerr;/*      0 1 2 3 4 5 6   + - * / ( ) #  0+ > > < < < > >  1- > > < < < > >  2* > > > > < > >  3/ > > > > < > >  4( < < < < < =   5) > > > >   > >  6# < < < < <   =*//*> 2< 1= 0*/BYTE order[7][7] = {{2,2,1,1,1,2,2},{2,2,1,1,1,2,2},{2,2,2,2,1,2,2},{2,2,2,2,1,2,2},{1,1,1,1,1,0,255},{2,2,2,2,255,2,2},{1,1,1,1,1,255,0}};int Getloc(char achar) {switch (achar) {case ‘+‘:return 0;case ‘-‘:return 1;case ‘*‘:return 2;case ‘/‘:return 3;case ‘(‘:return 4;case ‘)‘:return 5;case ‘#‘:return 6;}return -1; //會引發異常}int domath(int a, char opt, int b) {switch (opt) {case ‘+‘:return a + b;case ‘-‘:return a - b;case ‘*‘:return a * b;case ‘/‘:if (b == 0){throw "Division by zero condition!";}return a / b;}return -1;}char transorder(char top, char c) {int x, y;y = Getloc(top);x = Getloc(c);return order[y][x];}int main(){stack<char> OPTR;stack<int> OPND;char c;OPTR.push(‘#‘);c = getchar();BOOL ISNUMBER = FALSE;while (c != ‘#‘ || OPTR.top()!=‘#‘) {if (c >= ‘0‘ && c <= ‘9‘) {if (ISNUMBER) {int tmp = OPND.top();OPND.pop();OPND.push(tmp * 10 + c - ‘0‘);c = getchar();continue;}ISNUMBER = TRUE;OPND.push(c - ‘0‘);c = getchar();}else {ISNUMBER = FALSE;switch (transorder(OPTR.top(), c)) {case 1:OPTR.push(c);c = getchar();break;case 0:OPTR.pop();c = getchar();break;case 2:int a, b;char opt = OPTR.top();OPTR.pop();b = OPND.top();OPND.pop();a = OPND.top();OPND.pop();try {OPND.push(domath(a,opt,b));}catch (const char * e) {cerr << e << endl;return 0;}break;}}}cout << OPND.top();return 0;}

 哎 寫的時候把運算元的類型也寫成char了 debug半天。。。

資料結構--算數運算式求值

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.