http://acm.hdu.edu.cn/showproblem.php?pid=1237
堆栈的简单应用
//hdu_1237 简单计算器 stack的应用
#include <cstdio>
#include <iostream>
#include <stack>
#include <cstring>
using namespace std;
stack<double > snum;
stack<char >sop;
int main()
{
int len, i;
double res, tmpa, tmpb;
char tmp;
char str[201];
while(gets(str)){
len = strlen(str);
if(len == 1 && str[0] == '0')break;
tmpa = 0;
for(i = 0; i < len; i ++){
if(str[i] == ' '){
i ++;
if(snum.empty()){//第一个操作数和第一个操作符
// printf("%lf\n", tmpa);
snum.push(tmpa);
sop.push(str[i]);
}
else{
if((sop.top() == '+'||sop.top() == '-') &&(str[i] == '*' || str[i] == '/')){
snum.push(tmpa);
sop.push(str[i]);
}
else{
snum.push(tmpa);
//处理相同的操作数和操作符
while(!sop.empty()){
if((sop.top() == '+'||sop.top() == '-') &&(str[i] == '*' || str[i] == '/'))break;
tmpa = snum.top();
snum.pop();
tmp = sop.top();
sop.pop();
tmpb = snum.top();
snum.pop();
// printf("%c\n", tmp);
switch(tmp){
case '+':
res = tmpb + tmpa;
// printf("+%lf\n", tmpa);
snum.push(res);
break;
case '-':
res = tmpb - tmpa;
snum.push(res);
break;
case '*':
res = tmpb * tmpa;
snum.push(res);
break;
case '/':
res = tmpb*1.0/tmpa;
snum.push(res);
break;
}
}
sop.push(str[i]);
}
}
i += 1;
tmpa = 0;
}
else{
tmpa = tmpa * 10 + (int)(str[i] - '0');
// printf("%lf\n", tmpa);
}
}
snum.push(tmpa);
//做最后的处理
while(!sop.empty()){
tmpa = snum.top();
snum.pop();
tmp = sop.top();
sop.pop();
tmpb = snum.top();
snum.pop();
// printf("%c\n", tmp);
switch(tmp){
case '+':
res = tmpb + tmpa;
// printf("+%lf\n", tmpa);
snum.push(res);
break;
case '-':
res = tmpb - tmpa;
snum.push(res);
break;
case '*':
res = tmpb * tmpa;
snum.push(res);
break;
case '/':
res = tmpb*1.0/tmpa;
snum.push(res);
break;
}
}
printf("%.2lf\n", snum.top());
snum.pop();
}
return 0;
}