HDU1237 简单计算器 栈

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include<stack>
 5 #include<vector>
 6 using namespace std;
 7 int main()
 8 {
 9     char str[210];
10     while (1) {
11         stack<double>a;stack<char>b;
12         gets_s(str);
13         int len = strlen(str);
14         if (str[0] == '0'&&len==1)break;    
15         for (int i = 0;i < len;i++) {
16             if (str[i] == ' ')continue;
17             else if (str[i] != '+' && str[i] != '-' && str[i] != '*' && str[i] != '/') {
18                 double res = 0;
19                 while (str[i] != ' '&&i<len) {
20                     res = res * 10 + str[i] - '0';i++;
21                 }
22                 a.push(res);
23             }
24             else if (str[i] == '*' || str[i] == '/') {
25                 int pos = i;
26                 i+=2;
27                 double res = 0;
28                 while (str[i] != ' ' && i < len) {
29                     res = res * 10 + str[i] - '0';i++;
30                 }
31                 double ans = 0;
32                 if (str[pos] == '*')ans = a.top() * res;
33                 else if (str[pos] == '/')ans = a.top() / res;
34                 a.pop();
35                 a.push(ans);
36             }
37             else if (str[i] == '+' || str[i] == '-')b.push(str[i]);
38         }
39         vector<double>A;vector<char>B;
40         while (!a.empty())A.push_back(a.top()), a.pop();
41         while (!b.empty())B.push_back(b.top()), b.pop();
42         reverse(A.begin(), A.end());reverse(B.begin(), B.end());
43         double num = A[0];
44         for (int i = 1, j = 0;i<A.size(),j<B.size();j++,i++) {
45             if (B[j] == '+')num += A[i];
46             else num -= A[i];
47         }
48         printf("%.2f\n", num);
49     }
50 }
51 //先将优先级高的乘除运算掉
52 //4 + 2 * 5 - 7 / 11 变为  4+10-0.63

 

posted @ 2020-02-28 21:57  programmer_w  阅读(139)  评论(0编辑  收藏  举报