Arduino: инфикс в постфикс - PullRequest
       83

Arduino: инфикс в постфикс

0 голосов
/ 08 февраля 2020

Я хочу сделать калькулятор на Arduino, поэтому этот калькулятор должен содержать информацию о «последовательности операций».

Я верю, что мои коды «конвертации в постфикс» верны, но исполняемая программа перестает работать, и я получил результаты, которые не эффективны. Я пытаюсь этот код на других arduinos, но я не получаю результата. Запись на lcd иногда работает, но иногда код сбрасывает arduino. Я не понимаю, почему произошла эта ошибка.

#include <Keypad.h>
#include <LiquidCrystal.h>

const byte SATIR = 4;
const byte SUTUN= 4;
char keys[SATIR][SUTUN] = {
{'1','2','3','+'},
{'4','5','6','-'},
{'7','8','9','*'},
{'C','0','=','/'}
};

byte rowPins[SATIR] = { 13, 10, 9, 8 };
byte colPins[SUTUN] = { 7, 6, 1, 0 };
Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, SATIR, SUTUN );

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int SIZE = 20;
char stack[20];
int top = -1;
String num = "";
int number;

void setup() {
  lcd.begin(16, 2); //16x2 kullaniyoruz
  lcd.print("fatay"); 
  delay(3000);
  lcd.clear();
  lcd.setCursor(0, 0);
}

int p = 0;

void loop(){

  char infix[20];
  char postfix[20]; 

  char key = kpd.getKey();

  if (key != NO_KEY){
    if(key == '=') {
      for(int z = 0; z<num.length(); z++){
        infix[z] = num.charAt(z);
      }
      number = num.length();
      delay (100);
      InfixToPostfix(infix,postfix); 

    } else {
      lcd.print(key);
      num+=key;
      delay(400);
    }
  }

}



////////////////////////////////////////////////////////////////////////////////////////

void push(char item) {
  if(top >= SIZE-1)
  {
    printf("\nStack Overflow.");
  }
  else
  {
    top = top+1;
    stack[top] = item;
  }
}

/* define pop operation */
char pop() {
  char item ;

  if(top <0)
  {
    printf("stack under flow: invalid infix expression");
    getchar();
    /* underflow may occur for invalid expression */
    /* where ( and ) are not matched */
    exit(1);
  }
  else
  {
    item = stack[top];
    top = top-1;
    return(item);
  }
}

////////////////////////////////////////////////////////////////////////////////////////

int is_operator(char symbol) {
  if(symbol == '^' || symbol == '*' || symbol == '/' || symbol == '+' || symbol =='-')
  {
    return 1;
  }
  else
  {
  return 0;
  }
}



int precedence(char symbol) {
  if(symbol == '^')/* exponent operator, highest precedence*/
  {
    return(3);
  }
  else if(symbol == '*' || symbol == '/')
  {
    return(2);
  }
  else if(symbol == '+' || symbol == '-')          /* lowest precedence */
  {
    return(1);
  }
  else
  {
    return(0);
  }
}

void InfixToPostfix(char infix_exp[], char postfix_exp[])
{ 
  int i, j;
  char item;
  char x;

  push('(');                               /* push '(' onto stack */
  strcat(infix_exp,")");                  /* add ')' to infix expression */

  i=0;
  j=0;
  item=infix_exp[i];         /* initialize before loop*/

  while(item != '\0')        /* run loop till end of infix expression */
  {
    if(item == '(')
    {
      push(item);
    }
    else if( isdigit(item) || isalpha(item))
    {
      postfix_exp[j] = item;              /* add operand symbol to postfix expr */
      j++;
    }
    else if(is_operator(item) == 1)        /* means symbol is operator */
    {
      x=pop();
      while(is_operator(x) == 1 && precedence(x)>= precedence(item))
      {
        postfix_exp[j] = x;                  /* so pop all higher precendence operator and */
        j++;
        x = pop();                       /* add them to postfix expresion */
      }
      push(x);
      /* because just above while loop will terminate we have
      oppped one extra item
      for which condition fails and loop terminates, so that one*/

      push(item);                 /* push current oprerator symbol onto stack */
    }
    else if(item == ')')         /* if current symbol is ')' then */
    {
      x = pop();                   /* pop and keep popping until */
      while(x != '(')                /* '(' encounterd */
      {
        postfix_exp[j] = x;
        j++;
        x = pop();
      }
    }
    else
    { /* if current symbol is neither operand not '(' nor ')' and nor
      operator */
      printf("\nInvalid infix Expression.\n");        /* the it is illegeal  symbol */
      getchar();
      exit(1);
    }
    i++;


    item = infix_exp[i]; /* go to next symbol of infix expression */
  } /* while loop ends here */
  if(top>0)
  {
    printf("\nInvalid infix Expression.\n");        /* the it is illegeal  symbol */
    getchar();
    exit(1);
  }
  if(top>0)
  {
    printf("\nInvalid infix Expression.\n");        /* the it is illegeal  symbol */
    getchar();
    exit(1);
  }

delay(100);
lcd.setCursor(0,1);
delay (100);
  for(int k = 0; k<number; k++) {
      lcd.print(postfix_exp[k]);  

  }




}

Спасибо за ваш ответ заранее.

...