1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
|
#ifndef STACK_EVALUALGOR_H #define STACK_EVALUALGOR_H #define N_OPTR 9 #include "Stack.h" #include <cmath> #include "ParenMatch.h"
typedef enum {ADD,SUB,MUL,DIV,POW,FAC,L_P,R_P,EOE} Operator;
Operator optrRank(char optr){ switch (optr) { case '+' : return ADD; case '-' : return SUB; case '*' : return MUL; case '/' : return DIV; case '^' : return POW; case '!' : return FAC; case '(' : return L_P; case ')' : return R_P; case '\0' : return EOE; default: exit(-1);
} }
const char pri[N_OPTR][N_OPTR] = { '>','>','<','<','<','<','<','>','>', '>','>','<','<','<','<','<','>','>', '>','>','>','>','<','<','<','>','>', '>','>','>','>','<','<','<','>','>', '>','>','>','>','>','<','<','>','>', '>','>','>','>','>','>',' ','>','>', '<','<','<','<','<','<','<','=',' ', ' ',' ',' ',' ',' ',' ',' ',' ',' ', '<','<','<','<','<','<','<',' ','=', };
void readNumber(char*& S,Stack<float>& p){ p.push((float)(*S-'0')); while(isdigit(*(++S))) p.push(p.pop()*10+(*S-'0')); if('.' != *S) return; float xiaoshu = 1; while(isdigit(*(++S))) p.push(p.pop()+(*S-'0')*(xiaoshu/=10)); }
char orderBetween(char optr1,char optr2){ return pri[optrRank(optr1)][optrRank(optr2)]; }
int factorial(int n){ if(n<0) exit(-1); else if(n == 1) return 1; else return n*factorial(n-1); }
int calcu(char optr,int pOpnd){return factorial(pOpnd); }
float calcu(float pOpnd1,char optr,float pOpnd2) { if (optr == '/' && pOpnd2 == 0) exit(-1); switch (optr) { case '+' : return pOpnd1 + pOpnd2; break; case '-' : return pOpnd1 - pOpnd2; break; case '*' : return pOpnd1 * pOpnd2; break; case '/' : return pOpnd1 / pOpnd2; break; case '^' : return pow(pOpnd1, pOpnd2); default: exit(-1); } }
float evaluate(char *S) { if( ! paren(S,0,length(S)) ) exit(-1); else{ Stack<float> opnd; Stack<char> optr; optr.push('\0'); while (!optr.Empty()) { if (isdigit(*S)) { readNumber(S, opnd); } else switch (orderBetween(optr.top(), *S)) { case '<': optr.push(*S); S++; break; case '=': optr.pop(); S++; break; case '>': char op = optr.pop(); if ('!' == op) { float pOpnd = opnd.pop(); if ((int) pOpnd == pOpnd) { opnd.push(calcu(op, (int) pOpnd)); } else exit(-1);
} else { float pOpnd2 = opnd.pop(), pOpnd1 = opnd.pop(); opnd.push(calcu(pOpnd1, op, pOpnd2)); } break; } } return opnd.pop(); } }
#endif
|