안녕하세요. 언제나 휴일에 언휴예요.
이번에는 파서 트리를 이용한 계산기를 구현하는 실습이예요.
23+8*9-7 과 같은 수식을 계산하면 8*9를 먼저 계산하고 23+(8*9)-7 순으로 계산합니다.
이처럼 수식을 연산자 우선 순위에 맞게 계산하기 위해 여기에서는 파서 트리를 이용할 거예요.
파서 트리를 이용한 계산기에 관한 이론적인 내용은 자료구조와 알고리즘 C++ 9.3 수식 파서 트리를 참고하세요.
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 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 |
#include <string> #include <iostream> using namespace std; class Calculator { string expr; public: Calculator(string expr) { this->expr = expr; tcnt = 0; } void Run() { cout<<expr<<"을 계산합니다. ..."<<endl; if(Lexical()) { if(Syntax()) { Parsing(); PostOrderView(); cout<<expr<<"="<<Calculate()<<endl; } else { cout<<"수식에 사용한 표현이 문법에 맞지 않습니다."<<endl; } } else { cout<<"사용할 수 없는 기호가 있습니다."<<endl; } cout<<endl; } private: bool Lexical() { int i = 0; while(expr[i]) { if(IsOperator(expr[i])) { i = MakeOperator(i); } else { if(IsDigit(expr[i])) { i = MakeOperand(i); } else { return false; } } } return true; } bool IsOperator(char ch) { return (ch =='+')||(ch=='-')||(ch=='*')||(ch=='/'); } bool IsDigit(char ch) { return (ch>='0')&&(ch<='9'); } struct Token { int priority; virtual void View()=0; bool MoreThanPriority(Token *token) { return priority>=token->priority; } }; struct Operator:public Token { char ch; Operator(char ch) { this->ch = ch; if((ch=='+')||(ch=='-')) { priority = 1; } else { priority = 2; } } void View() { cout<<ch<<" "; } }; Token *tokens[100]; int tcnt; int MakeOperator(int i) { tokens[tcnt] = new Operator(expr[i]); tcnt++; return i+1; } struct Operand:public Token { int value; Operand(int value) { this->value = value; priority = 3; } void View() { cout<<value<<" "; } }; int MakeOperand(int i) { int value = 0; while(IsDigit(expr[i])) { value = value*10 + expr[i] - '0'; i++; } tokens[tcnt] = new Operand(value); tcnt++; return i; } bool Syntax() { if(tcnt%2==0) { return false; } if(tokens[0]->priority !=3) { return false; } for(int i = 1; i<tcnt; i+=2) { if(tokens[i]->priority==3) { return false; } if(tokens[i+1]->priority != 3) { return false; } } return true; } struct ParserTree { struct Node { Token *token; Node *lc; Node *rc; Node(Token *token) { this->token = token; lc = rc = 0; } }; Node *root; ParserTree(Token *token) { root = new Node(token); } void Add(Token *token) { Node *now = new Node(token); Token *st = root->token; if(st->MoreThanPriority(token)) { now->lc = root; root = now; } else { if(token->priority !=3) { now->lc = root->rc; root->rc = now; } else { Node *pa = root; while(pa->rc) { pa = pa->rc; } pa->rc = now; } } } void View() { PostOrder(root); cout<<endl; } void PostOrder(Node *sr) { if(sr) { PostOrder(sr->lc); PostOrder(sr->rc); sr->token->View(); } } int Calculate() { return PostOrderCalculate(root); } int PostOrderCalculate(Node *sr) { if(sr->lc) { int lvalue = PostOrderCalculate(sr->lc); int rvalue = PostOrderCalculate(sr->rc); Operator *op = dynamic_cast<Operator *>(sr->token); switch(op->ch) { case '+': return lvalue + rvalue; case '-': return lvalue - rvalue; case '*': return lvalue * rvalue; case '/': if(rvalue) { return lvalue / rvalue; } cout<<"divide zero error"<<endl; return 0; } throw "정의하지 않은 연산자입니다."; } Operand *op = dynamic_cast<Operand *>(sr->token); return op->value; } }; ParserTree *ps; void Parsing() { ps = new ParserTree(tokens[0]); for(int i = 1; i<tcnt;i++) { ps->Add(tokens[i]); } } void PostOrderView() { ps->View(); } int Calculate() { return ps->Calculate(); } }; int main() { string tc_exprs[6]= { "2+3-5*5+6/2", "23*5/2+4*6", "2+4*5#6", "2+3*5+", "3+36+-7", "45+3*5-2+5/2*7", }; for(int i = 0; i<6; i++) { Calculator *cal = new Calculator(tc_exprs[i]); cal->Run(); delete cal; } return 0; } |