c++ - 后置表达式求解器

标签 c++

目标是编写一个程序来解决后修复/反向波兰表示法表达式。这似乎是一件容易的事,但我似乎忽略了其中的错误。在此先感谢您的帮助。

vector<int> stack;
string input;

cout << "Please enter post-fix expression to be evaluated (+, -, *, /): ";
cin >> input;

for(int i=0; i<input.size(); i++)
{
    if(input[i] == '+')
    {
        int temp1 = stack.back();
        stack.pop_back();
        int temp2 = stack.back();
        stack.pop_back();

        int sum = temp1 + temp2;
        stack.push_back(sum);
    }
    else if(input[i] == '-')
    {
        int temp1 = stack.back();
        stack.pop_back();
        int temp2 = stack.back();
        stack.pop_back();

        int difference = temp1 - temp2;
        stack.push_back(difference);
    }
    else if(input[i] == '*')
    {
        int temp1 = stack.back();
        stack.pop_back();
        int temp2 = stack.back();
        stack.pop_back();

        int product = temp1 * temp2;
        stack.push_back(product);
    }
    else if(input[i] == '/')
    {
        int temp1 = stack.back();
        stack.pop_back();
        int temp2 = stack.back();
        stack.pop_back();

        int quotient = temp1 / temp2;
        stack.push_back(quotient);
    }
    else
    {
        stack.push_back(input[i]);
    }
}

cout << "Result: " << stack.back();

最佳答案

真正的问题是 stack.push_back(input[i]);您推回一个字符,例如“7”,这将导致 55 被压入堆栈。

关于c++ - 后置表达式求解器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26475891/

相关文章:

c++ - operator>>(,) 重载以一种令人惊讶的方式表现

c++ - 对 `boost::log_mt_posix::basic_attribute_set<char>::~basic_attribute_set()' 的 undefined reference

c++ - 按字母顺序排列的字符串

c++ - (iOS) 如何从 C++ 应用程序获取 UIViewController?

c++ - 可由设备或主机调用的 CUDA 函数

c++ - 传递给存储常量引用的成员的临时对象的生命周期

c++ - 使用稍旧版本的 GLIBCXX

c++ - Tensorflow Lite arm64 错误 : cannot convert ‘const int8x8_t?

c++ - Qt多行替代水平布局

c++ - 为什么我必须通过this指针访问模板基类成员?