0

我编写了这段代码来计算后缀表达式,但在这段代码中,我只能计算一个只有一位数的表达式。我想编辑此代码以评估多位数。我怎样才能做到这一点?

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

1 回答 1

3

对于多位数字,您需要一个分隔符,例如。空间。后缀中的所有标记都将用空格分隔。您需要一次读取一个令牌。例如,表达式“28 2 / 5 -”可以计算如下:

#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<int> s ;
    int dig = 0;
    int i=0;
    while(i<exp.length())
    {
        char e = exp[i];
        if(isdigit(exp[i])) {
            dig = dig*10 + (exp[i]-'0');
        } else if (exp[i] == ' ') {
            s.push(dig);
            dig = 0; 
        } else {
            float o2=s.top();
            s.pop();
            float o1=s.top();
            s.pop();
            result = calc(o1,o2,e);
            s.push(result);
            i++;

        }i++;
    }
    return s.top();
}

int main()
{
    string exp="28 2 / 5 -";
    cout<<evaluate(exp);
    return 0;
}

附加参考链接:多位数字的后缀评估

于 2021-09-13T20:03:12.547 回答