標籤:資料結構 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半天。。。
資料結構--算數運算式求值