【Weiss】【第03章】练习3.19:计算后缀表达式

【练习3.19】

编写一个程序计算后缀表达式的值。

Answer:

计算的方法书上说得很明白了,看代码行,没写错误检测【因为懒】。

测试代码:

 1 #include <iostream>
 2 #include "stack.h"
 3 using namespace std;
 4 using namespace stack;
 5 template class Stack<int>;
 6 int main(void)
 7 {
 8     calexp item[] = { (4.99), (1.06), ('*'), (5.99), ('+'), (6.99), (1.06), ('*'), ('+') };
 9     cout << postfix_exp(item, 9) << endl;
10         
11     system("pause");
12 }
View Code

实现代码:

 1 //练习3.19新增,计算后缀表达式,不包含表达式错误检测
 2 static enum CalExpType{ CALEXP_NUMBER, CALEXP_OPERATOR };
 3 //表达式元素,当元素类型为数值时则读取num,为操作符时则读取opera
 4 struct calexp
 5 {
 6 public:
 7     calexp(double _num) :elemtype(CALEXP_NUMBER), num(_num), opera(''){}
 8     calexp(char _opera) :elemtype(CALEXP_OPERATOR), num(0.0), opera(_opera){}
 9     CalExpType gettype(){ return elemtype; }
10     double getnum(){ return num; }
11     char getopera(){ return opera; }
12 private:
13     CalExpType elemtype;
14     double num;
15     char opera;
16 };
17 double postfix_exp(calexp item[], int size)
18 {
19     Stack<double> calculator;
20 
21     for (int i = 0; i != size; ++i)
22     {
23         //当元素类型为数值时则读取num入栈
24         if (item[i].gettype() == CALEXP_NUMBER)
25             calculator.push(item[i].getnum());
26         //为操作符时则读取opera,并取栈顶两元素计算合并后入栈
27         else
28         {
29             double first = calculator.getpop();
30             double second = calculator.getpop();
31             switch (item[i].getopera())
32             {
33             case '+':
34                 first += second; break;
35             case '-':
36                 first -= second; break;
37             case '*':
38                 first *= second; break;
39             case '/':
40                 first /= second; break;
41             default:
42                 throw runtime_error("error");
43             }
44             calculator.push(first);
45         }
46     }
47     //返回栈顶
48     return calculator.getfirst();
49 }
原文地址:https://www.cnblogs.com/catnip/p/4352604.html