简体   繁体   中英

c++ Evaluating expression operator precedence not working

I'm making a program that evaluates arithmetic expressions through use of stacks. My code functions and does the proper calculation of an expression for the most part, however; when it comes to long expressions it doesn't follow the precedence I set out with the if statements.

void doOp() {

int x = stoi(valStk.top());
valStk.pop();
int y = stoi(valStk.top());
valStk.pop();
string op = opStk.top();
opStk.pop();

double result;
string result2;
if (op == "*")
{
    result = x * y;
    valStk.push(to_string(result));
}
else if (op == "/")
{
    result = x / y;
    valStk.push(to_string(result));
}
else if (op == "+")
{
    result = x + y;
    valStk.push(to_string(result));
}
else if (op == "-")
{
    result = y - x;
    valStk.push(to_string(result));
}
else if (op == "=>")
{
    if (x=y || x>y )
    {
        result2 = "true";
        valStk.push(result2);
    }
    else
    {
        result2 = "false";
        valStk.push(result2);
    }
}
else if (op == "<=")
{
    if (x = y || x<y)
    {
        result2 = "true";
        valStk.push(result2);
    }
    else
    {
        result2 = "false";
        valStk.push(result2);
    }
}
}

int main() {

string expression;
string quit;
int counter = 1;

while (quit != "1")
{
    std::cout << "Enter an expression item " << counter << ": ";
    std::cin >> expression;
    checkStr(expression);
    std::cout << "Are you done entering expression? Enter 1 to quit. ";
    std::cin >> quit;
    counter++;
}

for (int i = 0; i < valStk.size(); i++)
{
    doOp();
}

std::cout << valStk.top() << endl;
}

shouldn't the compiler use the order of the if statements to create precedence?

The function doOp() handles the topmost values and the corresponding operation. This means, if + is at the top of the stack, it will be evaluated first. And if operator * comes second, it will be handled after + .

So, to answer the question, the order of if statements doesn't matter, but the order of the elements on the stack does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM