📄 表达式转换.cpp
字号:
#define MAXSIZE 64
typedef int datatype;
#include<stdio.h>
typedef struct
{
datatype data[MAXSIZE];
int top;
}seqstack;
seqstack s;
char in[20],out[20];
///////////////////////////////////////////////////////////
void setnull()
{
s.top=-1;
}
bool empty()
{
if(s.top>=0)
return false;
else
return true;
}
///////////////////////////////////////////////////////////
void push(int x)
{
if(s.top==MAXSIZE-1)
printf("上溢!(注意你输入的表达式是否正确!)");
else
{
s.top++;
s.data[s.top]=x;
}
}
///////////////////////////////////////////////////////////
datatype pop()
{
if(empty())
{
printf("下溢!(注意你输入的表达式是否正确!)");return NULL;
}
else
{
s.top--;
return(s.data[s.top+1]);
}
}
///////////////////////////////////////////////////////////
datatype top()
{
if(empty())
{
return NULL;
}
else
return(s.data[s.top]);
}
///////////////////////////////////////////////////////////
bool yx(char c1,char c2)
{
if((c1=='*' && c2!='/')||(c1=='/' && c2!='*')||(c1=='+' && c2=='(')||(c1=='-' && c2=='('))
return true;
else
return false;
}
///////////////////////////////////////////////////////////
void input()
{
scanf("%s",&in);
}
void zzh()
{
setnull();
int i=0,j=0,k=0;
while(in[i]!=0)
{
if(in[i]>47)
{
out[j]=in[i];
j++;
}
else
{
if(empty())
push(in[i]);
else
{
if(in[i]=='(')
{
push(in[i]);
}
else if(in[i]==')')
{
while(top()!='(')
{
out[j]=pop();
j++;
}
pop();
}
else
{
while(!yx(in[i],top()) && !empty())
{
out[j]=pop();
j++;
}
push(in[i]);
}
}
}
i++;
}
while (!empty())
{
out[j]=pop();
j++;
}
}
///////////////////////////////////////////////////////////
int count()
{
int i=0,a,b;
setnull();
while(out[i]!=0)
{
if(out[i]>47)
{
push(out[i]-48);
}
else
{
if(out[i]=='+')
{
b=pop();
a=pop();
a=a+b;
push(a);
}
if(out[i]=='-')
{
b=pop();
a=pop();
a=a-b;
push(a);
}
if(out[i]=='*')
{
b=pop();
a=pop();
a=a*b;
push(a);
}
if(out[i]=='/')
{
b=pop();
a=pop();
a=a/b;
push(a);
}
}
i++;
}
return pop();
}
void main()
{int n;
do
{
printf(" ************************\n");
printf(" *欢迎使用表达式转换工具*\n");
printf(" ************************\n");
printf(" 注意--中缀表达式中只包含4种2目运算符:+,-,*,/ \n");
printf(" 及两种优先级运算符“(”和“)”\n");
printf(" 中缀表达式中不包含多余的空格。\n");
printf("请输入标准中缀表达式:\n");
input();
zzh();
printf("\n后缀表达式为:\n%s",out);
printf("\n\n结果:%s=%d\n\n",in,count());
printf(" 是否再次进行表达式转换?\n");
printf(" 是请按任意键. 否请输入0\n");
scanf("%c",&n);
}
while(getchar()!='0');
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -