//严蔚敏
#include<iostream>
#include"stackv.h"
#include<string>
double opt(double x,double z,double y)
{
//x=x-48;
//y=y-48;
double c=0;
if(z==43)
{
c=x+y;
}
if(z==45)
{
c=x-y;
}
if(z==42)
{
c=x*y;
}
if(z==47)
{
c=x/y;
}
return c;
}
int opr(double o1,double o2) //返回1为大于,2为小于,3为等于,4为错误
{
int t=0;
if(o1=='+')
{
if(o2=='+'||o2=='-'||o2==')'||o2=='#')
{
t=1;
}
else
{
t=2;
}
}
if(o1=='-')
{
if(o2=='+'||o2=='-'||o2==')'||o2=='#')
{
t=1;
}
else
{
t=2;
}
}
if(o1=='*')
{
if(o2=='(')
{
t=2;
}
else
{
t=1;
}
}
if(o1=='/')
{
if(o2=='(')
{
t=2;
}
else
{
t=1;
}
}
if(o1=='(')
{
if(o2==')')
{
t=3;
}
else if(o2=='#')
{
t=4;
}
else
{
t=2;
}
}
if(o1==')')
{
if(o2=='(')
{
t=4;
}
else
{
t=1;
}
}
if(o1=='#')
{
if(o2==')')
{
t=4;
}
else if(o2=='#')
{
t=3;
}
else
{
t=2;
}
}
return t;
}
void main()
{
double x,y,z,r=0,temp=0,d=0,f=0,g=0,zm=0; //数据定义模块
Stackv lp; //定义栈
Init(lp); //必须初始化,否则程序崩溃!
Push(lp,'#'); //使符栈栈底为'#'
Stackv rp;
Init(rp);
cout<<"请输入一个式子y,以“#”结束:"<<endl; //式子输入模块
cout<<"y = ";
char c=getchar();
while(c!='#'||Top(lp)!='#') //注意第二个井号的写入
{
if(c==' ')
{
cerr<<endl<<"输入有误!"<<endl<<endl;
exit(1);
}
if(c=='9'||c=='8'||c=='7'||c=='6'||c=='5'||c=='4'||c=='3'||c=='2'||c=='1'||c=='0'||c=='.')
{
if(c=='9'||c=='8'||c=='7'||c=='6'||c=='5'||c=='4'||c=='3'||c=='2'||c=='1'||c=='0')
{
temp=temp*10+(c-'0');
}
if(c=='.') //小数
{
d=1;
}
c=getchar();
if(d==1)
{
f++;
}
}
else if(c=='+'||c=='-'||c=='*'||c=='/'||c=='('||c==')'||c=='#')
{
while(f>1)
{
temp=temp/10;
f--;
}
if(r==0&&zm!=1)
{
Push(rp,temp);
temp=0;
d=0;
}
zm=0;
switch(opr(Top(lp),c))
{
case 1:
r=1;
z=Pop(lp);
y=Pop(rp); //cout<<y<<endl;
x=Pop(rp); //cout<<x<<endl;
//cout<<opt(x,z,y)<<endl;
Push(rp,opt(x,z,y));
break;
case 2:
Push(lp,c);
if(c=='+'||c=='-'||c=='*'||c=='/'||c=='(')
{
g=1;
}
c=getchar();
if(g==1&&c=='#')
{
g=0;
cerr<<endl<<"输入有误!"<<endl<<endl;
exit(1);
}
if(c=='9'||c=='8'||c=='7'||c=='6'||c=='5'||c=='4'||c=='3'||c=='2'||c=='1'||c=='0'||c=='.') //-( 连续的问题
{
r=0;
}
else if(c=='+'||c=='-'||c=='*'||c=='/'||c=='('||c==')'||c=='#')
{
r=1;
}
break;
case 3:
r=1;
Pop(lp);
c=getchar();
if(c=='(') //解决()()
{
cerr<<endl<<"输入有误!"<<endl<<endl;
exit(1);
}
break;
case 4:
r=0;
cerr<<endl<<"输入有误!"<<endl<<endl;
exit(1);
}
}
else //xx字母等
{
c=getchar();
if(c=='+'||c=='-'||c=='*'||c=='/'||c=='('||c==')'||c=='#')
{
zm=1;
}
}
}
printf("\ny = %f\n\n",Top(rp));
}