题目链接
这个题刚刚做过。是一个c++的实验课,所以我直接用别人的代码了
当然,博客上的代码是我自己的。
#include<iostream>
#include<stack>
#include<cctype>
using namespace std;
char priority[7][7]={
{'<','<','<','<','>','>','>'},
{'<','<','<','<','>','>','>'},
{'>','>','<','<','>','>','>'},
{'>','>','<','<','>','>','>'},
{'>','>','>','>','>','=','>'},
{'<','<','<','<','=','0','>'},
{'<','<','<','<','>','<','='}
};
int detect(char temp)
{
char oper[7]={'+','-','*','/','(',')','#'};
for(int i=0;i<7;i++)
{
if(temp==oper[i])
{
return i;
}
}
return 0;
}
char comp(char op1,char op2)
{
int row=detect(op1);
int col=detect(op2);
return priority[row][col];
}
int caclu(int n1,int n2,char op)
{
switch( op)
{
case '+':
return n1+n2;
break;
case '-':
return n1-n2;
break;
case '*':
return n1*n2;
break;
case '/':
if(n2==0)
{
cout<<"error // n2 is zero"<<endl;
return 0;
}
int tempResult=n1/n2;
return tempResult;
break;
}
return 0;
}
int main()
{
stack<int> intStack;
stack<char> opStack;
string input;
cin>>input;
opStack.push('#');
int temp=0;
int n=input.size();
for(int i=0;i<n;i++)
{
if(isdigit(input[i]))
{
temp*=10;
temp+=input[i]-'0';
if(!isdigit(input[i+1]))
{
intStack.push(temp);
temp=0;
}
}
else
{
here:
char compRes=comp(input[i],opStack.top());
switch (compRes)
{
case '=':
opStack.pop();
break;
case '<':
{
int tempN1=intStack.top();
intStack.pop();
int tempN2=intStack.top();
char tempOp=opStack.top();
opStack.pop();
intStack.pop();
int tempResult=caclu(tempN2,tempN1,tempOp);
intStack.push(tempResult);
goto here;
break;
}
case '>':
opStack.push(input[i]);
break;
}
}
}
cout<<intStack.top();
}
本文介绍了一个使用C++实现的表达式求值程序。该程序利用栈来处理操作数和运算符,并通过自定义的优先级矩阵来决定运算顺序。文章提供了完整的源代码,并解释了如何读取输入字符串并计算其结果。
5万+

被折叠的 条评论
为什么被折叠?



