我编写了这段代码来计算后缀表达式,但在这段代码中,我只能计算一个只有一位数的表达式。我想编辑此代码以评估多位数。我怎样才能做到这一点?
#include <iostream>
#include <stack>
#include <string>
using namespace std;
float calc(float o1,float o2,char c)
{
if(c=='+') return o1+o2;
if(c=='-') return o1-o2;
if(c=='*') return o1*o2;
if(c=='/') return o1/o2;
else return 0;
}
float evaluate(string exp)
{
float result=0;
stack<char>s;
for(int i=0;i<exp.length();i++)
{
if(isdigit(exp[i]))
{
s.push(exp[i]-'0');
}
else
{
float o2=s.top();
s.pop();
float o1=s.top();
s.pop();
result = calc(o1,o2,exp[i]);
s.push(result);
}
}
return s.top();
}
int main()
{
string exp="382/+5-";
cout<<evaluate(exp);
return 0;
}