中缀后缀评估一元否定

时间:2013-12-04 20:26:14

标签: c++ postfix-notation infix-notation unary-operator

我确定已经问过几次,但我看到的其他问题并没有给我带来太多帮助。好吧就是这样:我有三个函数,一个将中缀表达式转换为后缀,一个是预处理器,另一个是后缀表达式。我遇到麻烦的是评估一元的否定表达。如果我输入我的整个代码,它会超长,所以我只会发布处理负面/负面情况的部分:

这是我的输出:      输入:-3
     预处理后:3      postfix = -3      然后在输出时出现分段错误"总数= -3"

#include "postfix.h"
#include "stack.h"
#include <cstdlib>
#include <cmath>
#include <cstdio>

void eval_postfix(char* postfix){
  Stack<double> stack;
  char fchar[100];
  int j=0;
  double a, b, convert, total = 0.0;
  for(int i=0; postfix[i] != '\0'; i++){
    switch(postfix[i]){
    case '-':
      a = stack.top();
      stack.pop();
      b = stack.top();
      stack.pop();
      total = b-a;
      stack.push(total);
      break;

我非常确定错误是在函数的那一部分,我一直在尝试不同的事情,但没有任何工作,更多次是我得到分段错误或零。我最初尝试应用我在infix2postfix表达式中所做的事情(显然没有工作)但是我的代码的其余部分用于负面/负面情况...

void infix2postfix(char* infix, char* postfix){
  Stack<char> stack;
  stack.push('\0');
  int pc = 0;
  bool c;
  for(unsigned int i = 0; infix[i] != '\0'; i++){
    //use the switch method to define what to do for each of the operators
    switch(infix[i]){
 case '-':
      c = 0;
      //unary negative
      if(i==0){
    postfix[pc++] = infix[i];
    c = 1;
      }
      else if((infix[i-1] == '*' ||
           infix[i-1] == '^' ||
           infix[i-1] == '*'  ||
           infix[i-1] == '/'  ||
           infix[i-1] == '+' ||
           infix[i-1] == '-')&& 
          i>0){
    postfix[pc++]= infix[i];
    c=1;
      }
      else{
    if(stack.top() == '*' || stack.top() == '/' || stack.top() == '^'){
      while(stack.top() != '\0' && stack.top() != '('){
        postfix[pc++] = stack.top();
        postfix[pc++] = ' ';
        stack.pop();
      }
    }
      }
      if (c==0)
    stack.push('-');
      break;

void preprocessor(char* input){
      char output[100];
      int oc = 0;
      for(unsigned int i=0; input[i] != '\0'; i++){
        if((input[i] == '-' && (input[i-1] == '*' || input[i-1] == '^' || input[i-1] == '*'
                    || input[i-1] == '/' || input[i-1] == '+' || input[i-1] == '-')
        && i>0)){
          //output[oc++] = '0';
          output[oc++] = input[i];
        }

我几乎可以肯定,无论我犯了什么错误(或者我需要做什么编辑)都可能是一件非常简单的事情,我无法看到(因为通常情况如此)和我在一起)但是对正确方向的任何推动都会受到高度赞赏!

**注意:我的代码格式可能不准确,因为我只复制并粘贴了我觉得相关的部分。

1 个答案:

答案 0 :(得分:0)

在我看来,正如所发生的那样,评估后缀表达式的代码在看到减号时会将其视为减法。特别是,可能你将3推入堆栈,然后遇到一个减号:这会触发你发布的第一个块中的代码,它会尝试从堆栈中弹出两个元素并减去它们。但是,堆栈中只有一个元素,即3。

相关问题