C 评估表达操作员优先级不起作用

c++ Evaluating expression operator precedence not working

本文关键字:优先级 不起作用 操作员 评估      更新时间:2023-10-16

我正在制作一个程序,通过使用堆栈来评估算术表达式。我的代码功能功能,并在大多数情况下对表达式进行适当的计算;当涉及长表达式时,它不遵循我从if语句中列出的优先级。

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

编译器不应该使用if语句的顺序创建优先级吗?

函数doOp()处理最高值和相应的操作。这意味着,如果+位于堆栈的顶部,则将首先对其进行评估。如果操作员*排名第二,则将在+之后进行处理。

所以,要回答问题,if语句的顺序无关紧要,但是堆栈上的元素的顺序确实如此。