Creating a Reverse Polish Rotation Calculator in C

Asked

Viewed 183 times

1

need to do for an exercise an RPN calculator only for cases (+ - / * ), through batteries, it is necessary that the input is of type ABC+*, that the program understands this, the user of the values of A,B and C, and, through the battery system, calculate the result of the account, so far I have it:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAXTAM 51

typedef struct {
  char Item[MAXTAM];
  int Topo;
} TPilha;

void TPilha_Iniciar (TPilha *p) {
  p->Topo = -1;
}

int TPilha_Vazia (TPilha *p) {
  if (p->Topo == -1) {
    return 1;
  } else {
    return 0;
  }
}

int TPilha_Inserir (TPilha *p, int x) {
  if (p->Topo == MAXTAM){
    return 0;
  } else {
    p->Topo++;
    p->Item[p->Topo] = x;
    return 1;
  }
}

float TPilha_Remover (TPilha *p) {
  int aux;
  if (TPilha_Vazia(p) == 1 ) {
    return 0;
  } else {
    aux = p->Item[p->Topo];
    p->Topo--;
    return 1;
  }
}

int main() {
  int count = 0;
  char arranjo[MAXTAM];
  scanf("%s", arranjo);
  int tamanho = strlen(arranjo);
  int i;
  for(i=0;i<=tamanho;i++) {
    if(isalpha(arranjo[i])){
      count++;
    }
  }
  float arranjov[count];
  for(i=0;i<count;i++) {
    scanf("%f", &arranjov[i]);
  }
 return 0; 
}

As you can see, I was able to create the battery system, the scan of the type string ABC+*and the scan of the values the user wants to assign to A, B and C. The problem now arises, how can I do the stacking/pop-up process in the Inverse Polish Notation system? I thought I’d use switch()with each case of + * - /, but I don’t know how to reconcile this with the batteries. Thanks in advance.

  • http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm#C

1 answer

1


It’s not an algorithm I’ve had before, but it fits the compilers. You have tried to use something similar to shift reduce, stack the numbers until you find a signal token (-+*/) pops with the arithmetic operation using the switch and in the loop, as you find the math signals.

4 8 9 + -

empilhar 4
empilhar 4 8
empilhar 4 8 9
empilhar 4 8 9 +
calcular 4 (8+9)
reduzir  4 17
empilhar 4 17 -
calcular 4 - 17
retornar 13 (if novo token == 0, final de string, \n)

See if this helps.

  • It gives to play nice there, a very interesting challenge.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.