#2
yangtya2017-03-21 17:21
|
#include<iostream>
#include<string.h>
#include<cstdlib>
using namespace std;
#define Max 1000
struct s1
{
float n[Max];
int top;
}stack1 ;
struct s2
{
char n[Max];
int top;
}stack2;
int isempty(s1 s)
{
if (s.top==-1)
return 1;
else
return 0;
}
int isempty2(s2 s)
{
if (s.top==-1)
return 1;
else
return 0;
}
void push1(s1 &s,float x)
{
if(s.top==Max-1)
{
cout<<"too much"<<endl;
return;
}
s.top++;
s.n[s.top]=x;
}
void push2(s2 &s,char x)
{
if(s.top==Max-1)
{
cout<<"too much"<<endl;
return;
}
s.top++;
s.n[s.top]=x;
}
void pop1(s1 &s,float &e)
{
if(s.top==-1)
{
cout<<"empty"<<endl;
return;
}
e=s.n[s.top];
s.top--;
}
void pop2(s2 &s,char &e)
{
if(s.top==-1)
{
cout<<"empty"<<endl;
return;
}
e=s.n[s.top];
s.top--;
}
int in(char e)
{
if(e=='+'||e=='-')
return 2;
else if(e=='*'||e=='/')
return 4;
else
{
cout<<"error"<<endl;
return -1;
}
}
int out(char e)
{
if(e=='+'||e=='-')
return 2;
else if(e=='*'||e=='/')
return 4;
else
{
cout<<"error"<<endl;
return -1;
}
}
void count(float &x,char &e,float &y)
{
float sum;
if(e=='+')
sum=x+y;
if(e=='-')
sum=x-y;
if(e=='*')
sum=x*y;
if(e=='/')
sum=x/y;
push1(stack1,sum);
}
int main()
{
long len,i=0,j,g;
char line[Max],operate,temp[20];
float a,b;
cout<<"input the operation expression"<<endl;
cin>>line;
len=strlen(line);
stack1.top=-1;
stack2.top=-1;
while(1)
{
g=0;
if(isdigit(line[i]))
{
j=0,g=1;
while(isdigit(line[i])||line[i]=='.')
{
temp[j++]=line[i];
i++;
if(i>=len)
break;
}
temp[j]='\0';
b=atof(temp);
push1(stack1,b);
i++;
if(i>=len)
break;
}
else
{
if(line[i]!='+'||line[i]!='-'||line[i]!='*'||line[i]!='/')
cout<<"mistake in expression"<<endl;
else{
if(!isdigit(line[i+1]))
cout<<"mistake in expression"<<endl;
else
{
g=1;
if(line[i]=='-'&&i==0)
{
push1(stack1,0);
push2(stack2,line[i]);
}
else
{
if(in(stack2.n[stack2.top])<out(line[i])||isempty2(stack2))
{
push2(stack2,line[i]);
i++;
}
else if(in(stack2.n[stack2.top])==out(line[i]))
{
i++;
push2(stack2,line[i]);
}
else
{
pop1(stack1,a);
pop1(stack1,b);
pop2(stack2,operate);
count(b,operate,a);
}
}
}
}
}
while(stack2.top!=-1)
{
pop1(stack1,a);
pop1(stack1,b);
pop2(stack2,operate);
count(b,operate,a);
}
}
cout<<stack1.n[stack1.top]<<endl;
return 0;
}