1
class Program
2
{
3
static void Main(string[] args)
4
{
5
char[,] cOperTable =
6
{
7
{ '>', '>', '<', '<', '<', '>', '>' },
8
{ '>', '>', '<', '<', '<', '>', '>' },
9
{ '>', '>', '>', '>', '<', '>', '>' },
10
{ '>', '>', '>', '>', '<', '>', '>' },
11
{ '<', '<', '<', '<', '<', '=', ' ' },
12
{ '>', '>', '>', '>', ' ', '>', '>' },
13
{ '<', '<', '<', '<', '<', ' ', '=' }
14
};
15
16
string strExp = "1+2-3-(3+2*8)*2#";
17
string strOpe = "+-*/()#"; // 0 1 2 3 4 5 6 7
18
Stack vStack = new Stack(); //值栈
19
Stack oStack = new Stack(); //操作符栈
20
oStack.Push('#');
21
22
for (int i = 0; i < strExp.Length; i++)
23
{
24
char c = strExp[i];
25
26
while (c != '#' || (char)oStack.Peek() != '#')
27
{
28
if (char.IsNumber(c))
29
{
30
vStack.Push(c); break;
31
}
32
else
33
{
34
bool goNext = true;
35
36
switch(cOperTable[strOpe.IndexOf((char)oStack.Peek()),strOpe.IndexOf(c)])
37
{
38
case '<':oStack.Push(c);break;
39
case '=':oStack.Pop(); break;
40
case '>':
41
char theta = (char)oStack.Pop(); //操作符
42
object b = vStack.Pop();
43
object a = vStack.Pop();
44
int ib = 0;
45
int ia = 0;
46
47
if (b is char) ib = (int)(char)b - 48;
48
else if (b is int) ib = (int)b;
49
if (a is char) ia = (int)(char)a - 48;
50
else if (a is int) ia = (int)a;
51
52
vStack.Push(Operate(ia, theta, ib));
53
break;
54
}//end switch
55
56
if (goNext) break;
57
}
58
}//exit while
59
}//exit for
60
61
Console.WriteLine("{0}",vStack.Pop());
62
Console.ReadKey();
63
}
64
65
static int Operate(int a, char theta, int b)
66
{
67
switch (theta)
68
{
69
case '+': return a + b;
70
case '-': return a - b;
71
case '*': return a * b;
72
case '/': return a / b;
73
default: return 0;
74
}
75
}
76
}

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
