﻿HDU 1237 简单计算器（栈、串的应用）-Ocrosoft

# 简单计算器

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 17693    Accepted Submission(s): 6206

Problem Description

Input

Output

Sample Input
```
1 + 2
4 + 2 * 5 - 7 / 11
0

```

Sample Output
```
3.00
13.36

```

Solution

```#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <conio.h>
#include <cmath>
#include <algorithm>
#include <list>
#include <stack>
#include <string>
#include <vector>
#include <cstring>
#include <cctype>
#define ms(a) memset(a,0,sizeof(a))
using namespace std;
stack<char> sop;
char s[1200],postexp[1200];
double res;
void Trans()
{
while(!sop.empty())
sop.pop();
int i=0,j=0;
char ch;
while(s[i])
{
ch=s[i];
if(ch=='(')
sop.push(ch);
else if(ch==')')
{
while(!sop.empty()&&sop.top()!='(')
{
postexp[j++]=sop.top();
sop.pop();
}
sop.pop();
}
else if(ch=='+'||ch=='-')
{
while(!sop.empty()&&sop.top()!='(')
{
postexp[j++]=sop.top();
sop.pop();
}
sop.push(ch);
}
else if(ch=='*'||ch=='/')
{
while(!sop.empty()&&sop.top()!='('&&(sop.top()=='*'||sop.top()=='/'))
{
postexp[j++]=sop.top();
sop.pop();
}
sop.push(ch);
}
else if(ch==' ')
{
i++;
continue;
}
else
{
while(ch>='0'&&ch<='9')
{
postexp[j++]=ch;
i++;
if(s[i])ch=s[i];
else break;
}
i--;
postexp[j++]='#';
}
i++;
}
while(!sop.empty())
{
postexp[j++]=sop.top();
sop.pop();
}
postexp[j++]='\0';
}
bool solve()
{
stack<double> st;
double a,b,c,d;
int i=0;
char ch;
int len=strlen(postexp);
while(i<len)
{
ch=postexp[i];
switch(ch)
{
case '+':
a=st.top(),st.pop();
b=st.top(),st.pop();
c=b+a;
st.push(c);
break;
case '-':
a=st.top(),st.pop();
b=st.top(),st.pop();
c=b-a;
st.push(c);
break;
case '*':
a=st.top();
st.pop();
b=st.top();
st.pop();
c=b*a;
st.push(c);
break;
case '/':
a=st.top(),st.pop();
b=st.top(),st.pop();
if(a!=0)
{
c=b/a;
st.push(c);
}
else return false;
break;
default:
d=0;
while(ch>='0'&&ch<='9')
{
d=10*d+(ch-'0');
i++;
ch=postexp[i];
}
st.push(d);
}
i++;
}
res=st.top();
return true;
}
int main()
{
while(gets(s)!=NULL)
{
if(s[0]=='0'&&strlen(s)==1)break;
Trans();
if(solve())
printf("%.2lf\n",res);
else
cout<<"Error!\n";
}
return 0;
}
```