hdu 1237【简单计算器】

简单题,直接模拟,但是还是要仔细点。。。

View Code
 1 #include <iostream>
 2 #include <stack>
 3 #include <iomanip>
 4 #include <ios>
 5 using namespace std;
 6 
 7 int main()
 8 {
 9     double a;
10     while(cin >> a)
11     {
12         stack<double> Snum;
13         stack<char> Sop;
14 
15         Snum.push(a);
16         char ch = getchar();
17         if(a == 0 && ch == '\n')
18             break;
19         while(ch != '\n')
20         {
21             ch = getchar();
22             Sop.push(ch);
23             cin >> a;
24             double tmp;
25             if(Sop.top() == '*')
26             {
27                 tmp = a * Snum.top();
28                 Snum.pop();
29                 Snum.push(tmp);
30                 Sop.pop();
31             }
32             else if(Sop.top() == '/')
33             {
34                 tmp = (Snum.top() / a);
35                 Snum.pop();
36                 Snum.push(tmp);
37                 Sop.pop();
38             }
39             else
40             {
41                 Snum.push(a);
42             }
43             ch = getchar();
44         }
45 
46         while(!Sop.empty())
47         {
48             double n1 = Snum.top();
49             Snum.pop();
50             double n2 = Snum.top();
51             Snum.pop();
52             double tmp;
53             if(Sop.top() == '+')
54             {
55                 Sop.pop();
56                 if(!Sop.empty() && Sop.top() == '-')
57                 {
58                     tmp = n2 - n1;
59                     Snum.push(tmp);
60                 }
61                 else
62                 {
63                     tmp = n1 + n2;
64                     Snum.push(tmp);
65                 }
66             }
67             else if(Sop.top() == '-')
68             {
69                 Sop.pop();
70                 if(!Sop.empty() && Sop.top() == '-')
71                 {
72                     tmp = n1 + n2;
73                     Snum.push(tmp);
74                 }
75                 else
76                 {
77                     tmp = n2 - n1;
78                     Snum.push(tmp);
79                 }
80             }
81         }
82 
83         double ans = Snum.top();
84         streamsize pre = cout.precision();
85         cout <<setprecision(2) << setiosflags(ios::fixed) <<  ans << setprecision(pre) << endl;
86     }
87 
88     return 0;
89 }
原文地址:https://www.cnblogs.com/Shirlies/p/2697561.html