你好)这是我的代码,用于从中缀表达式转换为后缀表达式,但是我不能理解如何计算我得到的后缀表达式,如果有任何提示,我将不胜感激。我不是在要求代码,尽管这将是有帮助的。
#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool operation(char b)
{
return b=='+' || b=='-' || b=='*' || b=='/' ;
}
bool priority(char a, char b)
{
if(a=='(')
{
return true;
}
if(a=='+' || a=='-')
{
return true;
}
if(b=='+' || b=='-')
{
return false;
}
return true;
}
int main()
{
string a;
string res;
stack<char> s;
cin>>a;
for(int i=0; i<a.size(); i++)
{
if(a[i]!='(' && a[i]!=')' && operation(a[i])==false)
{
res=res+a[i];
}
if(a[i]=='(')
{
s.push(a[i]) ;
}
if(a[i]==')')
{
while(s.top()!='(')
{
res+=s.top();
s.pop();
}
s.pop();
}
if(operation(a[i])==true)
{
if(s.empty() || (s.empty()==false && priority(s.top(), a[i])) )
{
s.push(a[i]);
}
else
{
while(s.empty()==false && priority(s.top(),a[i])==false )
{
res+=s.top();
s.pop();
}
s.push(a[i]) ;
}
}
}
while(s.empty()==false)
{
res+=s.top();
s.pop();
}
cout<<res;
return 0;
} 附注:我没有任何意见,但我认为代码本身是不言而喻的))
另外,提前谢谢你。
发布于 2014-03-02 22:39:37
如果你用空格隔开你的词缀表达式,下面将是编写赋值器的最简单的方法之一,只需跟随algorithm的求值即可
这里假设RPN类似于5 1 2 + 4 * + 3 - (用空格分隔)
int evaluate_posfix ( const std::string& expression )
{
int l,r,ans;
std::stringstream postfix(expression);
std::vector<int> temp;
std::string s;
while ( postfix >> s )
{
if( operation(s[0]) )
{
//Pull out top two elements
r = temp.back();
temp.pop_back();
l = temp.back();
temp.pop_back();
// Perform the maths
switch( s[0])
{
case '+': ans = l + r ; break;
case '-': ans = l - r ; break;
case '*': ans = l * r ; break;
case '/': ans = l / r ; break; // check if r !=0
}
temp.push_back( ans ); // push the result of above operation
}
else
{
temp.push_back( std::stoi(s) );
}
}
return temp[0] ; //last element is the answer
} https://stackoverflow.com/questions/22128772
复制相似问题