1 #include <iostream>
 2 #include <cstdio>
 3 #include <string>
 4 #include <stack>
 5 using namespace std;
 6 int main()
 7 {
 8     string s;
 9     while (getline(cin, s) && s != "0")
10     {
11         stack<double> ds;
12         stack<char> cs;
13         double t, t1, t2;
14         char c;
15         string::size_type i;
16         for (i = 0; i < s.size(); ++i)
17         {
18             if (s[i] >= '0' && s[i] <= '9')
19             {
20                 t = 0;
21                 while (s[i] >= '0' && s[i] <= '9')
22                 {
23                     t = t * 10 + s[i] - '0';
24                     ++i;
25                 }
26                 ds.push(t);
27             }
28             else if (s[i] == '+' || s[i] == '-')
29             {
30                 if (cs.empty())
31                     cs.push(s[i]);
32                 else
33                 {
34                     t1 = ds.top();
35                     ds.pop();
36                     t2 = ds.top();
37                     ds.pop();
38                     c = cs.top();
39                     cs.pop();
40                     if (c == '+')
41                         t = t1 + t2;
42                     else
43                         t = t2 - t1;
44                     ds.push(t);
45                     cs.push(s[i]);
46                 }
47             }
48             else if (s[i] == '*' || s[i] == '/')
49             {
50                 bool ismul = 0;                        //标记是乘号还是除号
51                 if (s[i] == '*')
52                     ismul = 1;
53                 i += 2;                                //求下个数字t2
54                 t2 = 0;
55                 while (s[i] >= '0' && s[i] <= '9')
56                 {
57                     t2 = t2 * 10 + s[i] - '0';
58                     ++i;
59                 }
60                 t1 = ds.top();
61                 ds.pop();
62                 if (ismul)
63                     t = t1 * t2;
64                 else
65                     t = t1 / t2;
66                 ds.push(t);
67             }
68         }
69         while (!cs.empty())                            //处理剩下的加减号
70         {
71             t1 = ds.top();
72             ds.pop();
73             t2 = ds.top();
74             ds.pop();
75             c = cs.top();
76             cs.pop();
77             if (c == '+')
78                 t = t1 + t2;
79             else
80                 t = t2 - t1;
81             ds.push(t);
82         }
83     printf("%.2f\n", ds.top());
84     }
85     return 0;
86 }

 

posted on 2013-03-30 11:50  PegasusWang  阅读(233)  评论(0编辑  收藏  举报