码迷,mamicode.com
首页 > 其他好文 > 详细

HDU1237 简单计算器 栈

时间:2020-02-28 22:28:45      阅读:59      评论:0      收藏:0      [点我收藏+]

标签:bsp   col   for   hdu   tor   +=   begin   vector   char   

 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

 

HDU1237 简单计算器 栈

标签:bsp   col   for   hdu   tor   +=   begin   vector   char   

原文地址:https://www.cnblogs.com/CSA01/p/12380511.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!