C 评估表达操作员优先级不起作用
c++ Evaluating expression operator precedence not working
我正在制作一个程序,通过使用堆栈来评估算术表达式。我的代码功能功能,并在大多数情况下对表达式进行适当的计算;当涉及长表达式时,它不遵循我从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
语句的顺序无关紧要,但是堆栈上的元素的顺序确实如此。
相关文章:
- 我的神经网络不起作用 [XOR 问题]
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- C++为什么尽管我调用了void函数,它却不起作用
- 为什么在保护模式下继承升级不起作用
- 循环在计数器中不起作用
- 在其他文件中创建类时在 c++ 项目中不起作用
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- 为什么二进制搜索在我的测试中不起作用
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 带有指定长度字符* 参数的 std::regex_search 在 VS2017 中不起作用?
- Bjarne Stroustrup Book - std_lib_facilities.h - 不起作用(未知类型名称)
- 为什么简单的算术减法在"if"条件下不起作用?
- 相等运算符优先级不起作用
- C 评估表达操作员优先级不起作用
- 中缀到后缀 - 优先级不起作用
- 优先级队列成员函数不起作用
- 使用 BST 的优先级队列 -- 删除最大不起作用
- ActiveMQ 3.8.3 (CPP) 优先级备份的问题不起作用