hdu 1237(模拟栈、水题)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1237

思路:模拟栈,先处理*和/的,算出结果后在入栈,将‘+’和‘-’入s栈,最后由于考虑加减运算符的优先级,还有倒一下栈。。这样就一共用到了4个栈。。。

View Code
 1 #define _CRT_SECURE_NO_WARNINGS
 2 #include<iostream>
 3 #include<cstdio>
 4 #include<cstring>
 5 #include<cmath>
 6 #include<stack>
 7 using namespace std;
 8 
 9 int main(){
10     char str[222];
11     while(gets(str),strcmp(str,"0")){
12         int len=strlen(str);
13         stack<double>S,SS;
14         stack<char>s,ss;
15         for(int i=0;i<len;i++){
16             if(str[i]==' ')continue;
17             else if(str[i]=='*'||str[i]=='/'){
18                 double x=S.top();
19                 S.pop();
20                 int j;
21                 double y=0;
22                 for(j=i+2;j<len;j++){
23                     if(str[j]!=' '){
24                         y=y*10+str[j]-'0';
25                     }else 
26                         break;
27                 }
28                 if(str[i]=='*')S.push(x*y);
29                 else S.push(x/y);
30                 i=j;
31             }else if(str[i]=='+'||str[i]=='-'){
32                 s.push(str[i]);
33             }else {
34                 int j;
35                 double x=0;
36                 for(j=i;j<len;j++){
37                     if(str[j]!=' '){
38                         x=x*10+str[j]-'0';
39                     }else 
40                         break;
41                 }
42                 S.push(x);
43                 i=j;
44             }
45         }
46         while(!S.empty()){
47             double x=S.top();
48             SS.push(x);
49             S.pop();
50         }
51         while(!s.empty()){
52             char ch=s.top();
53             ss.push(ch);
54             s.pop();
55         }
56         while(!SS.empty()&&!ss.empty()){
57             double x1=SS.top();
58             SS.pop();
59             double x2=SS.top();
60             SS.pop();
61             char ch=ss.top();
62             ss.pop();
63             if(ch=='+'){
64                 SS.push(x1+x2);
65             }else
66                 SS.push(x1-x2);
67         }
68         printf("%.2lf\n",SS.top());
69     }
70     return 0;
71 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值