📄 stack.cpp
字号:
#include <iostream>
using namespace std;
#include <stdio.h>
#include<assert.h>
#include <stack>
using namespace std;
int in(char c) //是符号就返回0,不是返回1。
{
int a;
switch (c)
{
case '+' :
case '-' :
case '*' :
case '/' :
case '(' :
case ')' :
case '#' : a=0; return a;break;
default : a=1; return a;break;
}
}
char precede(char b,char c)
{
char i,j,e,f;
char a[8][8];
a[1][0]=a[0][1]= '+' ;
a[2][0]=a[0][2]= '-' ;
a[3][0]=a[0][3]= '*' ;
a[4][0]=a[0][4]= '/' ;
a[5][0]=a[0][5]= '(' ;
a[6][0]=a[0][6]= ')' ;
a[7][0]=a[0][7]= '#' ;
for(i=1;i<8;i++)
for(j=1;j<8;j++)
a[i][j]='>';
a[6][5]=a[7][6]=a[5][7]=' ';
a[5][6]=a[7][7]='=';
for(i=1;i<6;i++)
a[5][i]=a[7][i]='<';
for(i=1;i<5;i++)
a[i][5]='<';
a[1][3]=a[1][4]=a[2][3]=a[2][4]='<';
for(i=1;i<8;i++)
{
if(b==a[i][0]) e=i;
if(c==a[0][i]) f=i;
}
return a[e][f]; //返回算符间的优先关系
}
int operate(int b,char theat ,int a)
{
int sum;
switch (theat)
{
case '+' : sum=a+b;break;
case '-' : sum=a-b;break;
case '*' : sum=a*b;break;
case '/' : sum=a/b;break;
}
return sum;
}
void main()
{
stack<int> opnd;
stack<char> optr;
char c,theta;
int sum,a,b,y,s=0;
optr.push('#');
cout<<"输入算术表达式子"<<endl;
c=getchar();
while(c!='#' || optr.top()!='#')
{
if(in(c))
{
c=c-48;s=s*10+c;
c=getchar();
if(c<'0') //下一个是符号.数字就进栈opnd
{opnd.push(s);s=0;}
}
else
{
switch (precede(optr.top(),c))
{
case '<' : optr.push(c);c=getchar();break; //栈顶元素优先权低
case '=' : optr.pop();c=getchar();break; //脱括号并接收下一个字符
case '>' : a=opnd.top();opnd.pop();
b=opnd.top();opnd.pop();
theta=optr.top();optr.pop();
if(a==0&&theta=='/') {y=a;cout<<"求值过程中有被除数是0,发生错误。"<<endl;break;}
opnd.push(operate(a,theta,b)); //退栈并将运算结果入栈
break;
}
if(y==0) break;
}
}
if (y!=0)
{
sum=opnd.top();
cout<<sum<<endl;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -