📄 yaoqin.cpp
字号:
#include<iostream>
using namespace std;
#define STACKSIZE 40
#define NEWSIZE 10
#define OK 1
#define ERROR 0
#define TURE 1
#define FALSE 0
#define OVERFLOW 0
typedef float ElemType1;
typedef char ElemType2;
typedef int status;
typedef struct stack1{
ElemType1 * top;
ElemType1 * base;
int stacksize;
}* STACK1; //此栈存放数据
typedef struct stack2{
ElemType2 * top;
ElemType2 * base;
int stacksize;
}* STACK2; //此栈存放操作符
int instack(char ch);
int iostack(char ch);
status initstack(STACK1 &S1,STACK2 &S2)
{
S2->base=(ElemType2 *)malloc(STACKSIZE * sizeof(ElemType2));
if(!S2->base)
{
cout<<"存储分配失败。\n";
return OVERFLOW;
}
else
{
S2->top=S2->base;
S2->stacksize=STACKSIZE;
*S2->top++='#';
}
S1->base=(ElemType1 *)malloc(STACKSIZE * sizeof(ElemType1));
if(!S1->base)
{
cout<<"存储分配失败。\n";
return OVERFLOW;
}
else
{
S1->top=S1->base;
S1->stacksize=STACKSIZE;
return OK;
}
}
status pushstack1(STACK1 &S1,float a)
{
*S1->top++=a;
return OK;
}
status pushstack2(STACK2 &S2,char ch)
{
*S2->top++=ch;
return OK;
}
float popstack1(STACK1 &S1)
{
float b;
b=*--S1->top;
return b;
}
char popstack2(STACK2 &S2)
{
char c;
c=*--S2->top;
return c;
}
char gettop(STACK2 &S2)
{
char c;
c=*(S2->top-1);
return c;
}
int judge(char ch)
{
int i;
char str;
str=ch;
switch(ch)
{
case '+':
case '-': i=2;break;
case '*':
case '/': i=4;break;
case '(': i=6;break;
case ')': i=1;break;
case '#': i=0;break;
}
return i;
}
float summit(char ch,float a,float b)
{
float i;
char c=ch;
switch(c)
{
case '+':
i=a+b;break;
case '-':
i=b-a;break;
case '*':
i=a*b;break;
case '/':
i=b/a;break;
}
return i;
}
float inputexpress(STACK1 &S1,STACK2 &S2)
{
int k=0;
float a,b,sum=0,data1,data2,result;
char c,ch,c_h,chh,p[25];
cout<<"请输入表达式,以#结尾!\n";
gets(p);
//cin.getline(p,25);
c=p[k];
while(c!='\0')
{
if(isdigit(c))
{
a=c;
sum=sum*10+a;
c=p[++k];
if(!isdigit(c))
{
pushstack1(S1,sum);
sum=0;
}
}
else
{
chh=gettop(S2);
while(chh!='#'||c!='#')
{
if(judge(c)>judge(chh))
{
pushstack2(S2,c);
break;
}
if(judge(c)<judge(chh))
{
if(c==')')
{
while(chh!='(')
{
ch=popstack2(S2);
data1=popstack1(S1);
data2=popstack1(S1);
result=summit(ch,data1,data2);
pushstack1(S1,result);
chh=gettop(S2);
}
c_h=popstack2(S2);
}
else
{
ch=popstack2(S2);
data1=popstack1(S1);
data2=popstack1(S1);
result=summit(ch,data1,data2);
pushstack1(S1,result);
chh=gettop(S2);
}
if(judge(c)==judge(chh))
break;
}
}
}
c=p[++k];
}//推出while循环
result=popstack1(S1);
return result;
}
void expressresult(float consequence)
{
float data;
data=consequence;
cout<<"\n\n"<<"此表达式的结果为:"
<<data<<endl;
}
status main()
{
float consequence;
STACK1 S1;
STACK2 S2;
initstack(S1,S2);
consequence=inputexpress(S1,S2);
expressresult(consequence);
return OK;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -