评估Postfix的功能始终导致1

时间:2017-10-14 23:41:54

标签: c++ postfix

以下是评估我的后缀表达式所涉及的功能:

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!输入无关紧要。我可以放入&#34; 5 2 /&#34;得到1.这对我没有意义,我不知道为什么会这样。如果有人可以帮助我,这将是惊人的,因为这项任务很快就会到期!

1 个答案:

答案 0 :(得分:0)

你应该在堆栈中获取top元素后弹出堆栈。 std :: stack :: pop()只返回堆栈的顶部元素,而不是pop操作。

import React, { Component } from 'react'; import '../../App.css'; class Card extends Component { render() { return ( <div className="carousel-item center"> <div className="card z-depth-4"> <div> <img src={this.props.src} className="responsive-img"/> </div> <p>{this.props.song}</p> <div className="singer">{this.props.singer}</div> </div> </div> ); } } export default Card; 更改为

float operand1 = S.top();

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

float operand2 = S.top();