例如:直接输入2+12*(5-1+(4/3))*2
我花了一个小时编出来的可能不完善你凑合着用罢
#include<iostream.h>
#include<stdlib.h>
#include<iomanip.h>
#include<string.h>
const int maxisize= 100;
struct element1 //构造double桟区结构
{
int top;
double data[maxisize];
};
struct element2 //构造char桟区结构
{
int top;
char data[maxisize];
};
element1 *init() //创建double 桟区
{
element1 *p=new element1;
p->top=-1;
return p;
}
element2 *initc() //创建 char桟区
{
element2 *p=new element2;
p->top=-1;
return p;
}
char precede(char a,char b) //precede() 输出优先级
{int i=0,j=0;
char ch[7]={'+','-','*','/','(',')','#' };
char prior[7][7]={
{'>','>','<','<','<','>','>' },
{'>','>','<','<','<','>','>' },
{'>','>','>','>','<','>','>' },
{'>','>','>','>','<','>','>' },
{'<','<','<','<','<','=','!' },
{'>','>','>','>','!','>','>' },
{'<','<','<','<','<','!','=' }} ;
while(ch[i]!=a)
{i++;}
while(ch[j]!=b)
{j++;}
return prior[i][j];
}
void push1(element1 *a, double b) //push1 double
{
a->data[++a->top]=b;
}
void push2(element2 *a, char b) //push2 char
{
a->data[++a->top]=b;
}
void zhikong(char *p) //将中间数组置空
{
strset(p,'\0');
}
double gettop1(element1 *p) //获得double 桟的尾元素但不删除
{
return p->data[p->top];
}
char gettop2(element2 *p) //获得char 桟的尾元素但不删除
{
return p->data[p->top];
}
double pop1(element1*a) //获得double 桟的尾元素并删除
{if(a->top==-1)
{
return 1;
}
else
return a->data[a->top--];
}
char pop2(element2*a) //获得char 桟的尾元素并删除
{if(a->top==-1)
{
return 1;
}
else
return a->data[a->top--];
}
int bijiao(char a) //ddddddddddddddddddd
{ int s=0;
char ch[7]={'+','-','*','/','(',')','#' };
for(int i=0;i<7;i++)
{if(ch[i]==a)
s=1;
}
return s;
}
double operate(double x,char b, double y)
{
switch(b)
{
case '+' :
return x+y ;
break ;
case '-' :
return x-y ;
break ;
case '*' :
return x*y ;
break ;
case '/' :
return x/y ;
break ;
default:return 0;break;
}
}
double jisuan(char *s)
{ element1 *x=init();
element2 *y=initc();
push2(y,'#');
int i=0;
int k=0;
int j=0;
char sjzjz[10];
while(s[i]!='#'||gettop2(y)!='#')
{
while(bijiao(s[i])==0)//dddddddddddddddddddd
{
sjzjz[k++]=s[i++];
}
if(k!=j)
{
push1(x,atof(sjzjz));
zhikong(sjzjz);
k=0;
}
else
{
switch(precede(gettop2(y),s[i]))
{
case '<':
{
push2(y,s[i]);
i++;
break;
}
case '=':
{
char x=pop2(y);
i++;
break;
}
case '>':
{
double x1,y1,result;
char opera;
x1=pop1(x);
y1=pop1(x);
opera=pop2(y);
result=operate(y1,opera,x1);
push1(x,result);
break;
}
}
}
}
delete y;
return gettop1(x);
delete x;
}
void main()
{
char shizi[maxisize];
int i;
loop:cout<<"<计算>(1)"<<" "<<"<退出>(0)"<<endl;
cin>>i;
switch (i)
{
case 1:
cout<<"输入多项式(注意不要用空格隔开):"<<endl;
cin>>shizi;
cout<<shizi<<setprecision(8)<<jisuan(shizi)<<endl;
break;
case 0:
exit(0);
default:
cout<<"please input 1 or 0"<<endl;
break;
}
goto loop;
}