后修复计算器,返回错误的值

Post fix calculator, returns wrong value

本文关键字:错误 返回 计算器      更新时间:2023-10-16

我正在编写一个程序来实现后缀计算器,它给了我完全错误的答案。真的很感谢帮助

class stacks {
public:
  typedef int List;
  static const int size = 100;
  stacks() {
    use = 0;
  }
  void push(List entry) {
    data[use] = entry;
    ++use;
  }
  List pop() {
    if(!empty()) {
      --use;
      return data[use];
    }
  }
  bool empty() const {
    return use == 0;
  }
  int Size() const {
    return use;
  }
private:
  List data[size];
  int use;
};
int main() {
  stacks s;
  string input;
  int final;
  ifstream infile("foo.txt",ios::in);
  while (getline(infile, input))
    cout << "Expression: ";
  for (int i = 0; i<input.length(); i++) {
    cout << input[i];
    auto oper1 = s.pop();
    auto oper2 = s.pop();
    if(input[i] == '1' || input[i] == '2' || input[i] == '3' || input[i] == '4' ||     nput[i] == '5' || input[i] == '6' || input[i] == '7' || input[i] == '8' || input[i] == '9')
      s.push(input[i] - '0');
    if(input[i] == '+')
      s.push(oper1 + oper2);
    if(input[i] == '-')
      s.push(oper1 - oper2);
    if(input[i] == '*')
      s.push(oper1 * oper2);
    if(input[i] == '/')
      s.push(oper1 / oper2);
  }
  final = s.pop();
  cout << endl << "Value = " << final << "." << endl << endl;
}

你有什么建议?谢谢

您需要等到知道您有运算符后再pop()。你正在从不应该的时候从堆栈中弹出东西。