gpt4 book ai didi

c++ - RPN 评估 C++

转载 作者:太空宇宙 更新时间:2023-11-04 13:54:26 25 4
gpt4 key购买 nike

你好)这是我将中缀表达式转换为后缀表达式的代码,但是我只是不明白如何评估我得到的后缀表达式,我将非常感谢任何提示。我不是要代码,尽管这会有所帮助。

#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;
}

附言我没有任何意见,但我想代码本身是不言自明的))
附言先感谢您。

最佳答案

如果您形成由空格分隔的 posfix 表达式,则以下将是对计算器进行编码的最简单方法之一,只需遵循 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
}

关于c++ - RPN 评估 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22128772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com