用栈实现计算器

 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 const int N = 256;
 5 char buf[N], optr[N];
 6 int opnd[N];
 7 int opndtop,optrtop;
 8 
 9 bool isDigit(char ch)
10 {
11     return ch >='0' && ch <='9';
12 }
13 
14 int pri(char op)
15 {
16     if (op=='(') return 0;
17     if (op=='+'|| op=='-') return 1;
18     if (op=='*'|| op=='/') return 2;
19 }
20 
21 void calculate()
22 {
23     int x,y;
24     y = opnd[--opndtop];
25     x = opnd[--opndtop];
26     char op = optr[--optrtop];
27     if (op == '+') x+=y;
28     if (op == '-') x-=y;
29     if (op == '*') x*=y;
30     if (op == '/') x/=y;
31     opnd[opndtop++] = x;
32 }
33 
34 int readnum(int &i)
35 {
36     int ret = 0;
37     while (isDigit(buf[i]))
38     {
39         ret=ret*10+buf[i++]-'0';
40     }
41     return ret;
42 }
43 
44 int main()
45 {
46     scanf("%s",buf+1);
47     buf[0]='(';
48     int len = strlen(buf);
49     buf[len] = ')';
50     buf[len+1] = '\0';
51     opndtop = optrtop = 0;
52     for (int i=0; buf[i]!='\0';)
53     {
54         if (isDigit(buf[i]))
55         {
56             int x = readnum(i);
57             opnd[opndtop++] = x;
58         }
59         else
60         {
61             char op = buf[i];
62             if (op=='(')
63                 optr[optrtop++] = op;
64             else if (op==')')
65             {
66                 while (optr[optrtop-1]!='(')
67                 {
68                     calculate();
69                 }
70                 optrtop--;
71             }
72             else
73             {
74                 while (pri(op)<pri(optr[optrtop-1]))
75                 {
76                     calculate();
77                 }
78                 optr[optrtop++] = op;
79             }
80             i++;
81         }
82     }
83     printf("%d\n",opnd[opndtop-1]);
84     return 0;
85 }

 

posted @ 2014-03-29 21:45  xzenith  阅读(337)  评论(0编辑  收藏  举报