计算后缀的函数总是结果为 1

Function to Evaluate Postfix Always Results in 1

本文关键字:结果 后缀 函数 计算      更新时间:2023-10-16

以下是计算我的后缀表达式所涉及的函数:

float postfixUtility::evaluatePostfix(string pexp)
{
stack<float> S;
int pexpLength = pexp.length();
for (int i = 0; i < pexpLength; i++)
{
    cout << pexp[i] << endl;
    if(pexp[i] == ' ' || pexp[i] == ',')
    { 
        continue;
    }     
    else if(isOperator(pexp[i]))
    { 
        float operand2 = S.top(); 
        //S.pop();
        float operand1 = S.top(); 
        //S.pop();
        float result = isOperate(pexp[i], operand1, operand2); 
        S.push(result);
    }
    else if(isDigit(pexp[i]))
    {   
        float operand = 0; 
        while(i<pexp.length() && isDigit(pexp[i]))
        {
            operand = (operand*10) + (pexp[i] - '0'); 
            i++;
        } 
        i--;
        S.push(operand);
    }
} 
return S.top();
}

bool postfixUtility::isDigit(char C) 
{
if(C >= '0' && C <= '9') 
{ 
    return true;
}
return false;
}

bool postfixUtility::isOperator(char C)
{
if(C == '+' || C == '-' || C == '*' || C == '/')
{
    return true;
}
return false;
}

float postfixUtility::isOperate(char operation, float operand1, float operand2)
{
if(operation == '+')
{   
    return operand1+operand2;
}
else if(operation == '-')
{
     return operand1-operand2;
}
else if(operation == '*')
{
     return operand1*operand2;
}
else if(operation == '/')
{   
    return operand1/operand2;
} 
}

问题是每次运行它时,我都会得到 1!输入无关紧要。我可以输入"5 2/"并得到 1。这对我来说没有意义,我不知道为什么会发生这种情况。如果有人能帮助我,那就太好了,因为这项任务很快就要到期了!

你应该在

堆栈中获取顶部元素后弹出堆栈。 std::stack::p op() 只返回堆栈的顶部元素,而不返回 pop 操作。

float operand1 = S.top();更改为

float operand1 = S.top();
S.pop();

并将float operand2 = S.top();更改为

float operand2 = S.top();
S.pop();