简体   繁体   English

评估表达式运算符优先级不起作用

[英]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. 当涉及长表达式时,它不遵循我为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;
}

shouldn't the compiler use the order of the if statements to create precedence? 编译器是否应该使用if语句的顺序来创建优先级?

The function doOp() handles the topmost values and the corresponding operation. 函数doOp()处理最高值和相应的操作。 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. 因此,要回答这个问题, if语句的顺序并不重要,但是堆栈上元素的顺序却无关紧要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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