I am trying to do operations using stack but at the time of allocating the results in the previous position in the stack it is that I am not succeeding because the result of the operation is not allocated in the desired position:
I'm trying to store in the previous position using but not the pointer does not pass the value.
p->topo--;
p->pElem [p->topo]=calc;
Order of operations
Operations:
A=9 B=3 C=2 D=1 E=1 1
1 1
3 3 2 2 2
PUSH A 9 -> PUSH B 9 -> SUB 9 (9-3) 6 -> PUSH C 6 -> PUSH D 6 -> PUSH E 6
1
1 1 1
2 2 2 3 3 2 2
MPY 6 (1x1) 6 -> ADD 6 (2+1) 6 -> DEC 6 (3-1) 6 -> DIV 6 (6/2) 3 -> POP F 3
Code:
#include<stdio.h>
#include<stdlib.h>
struct Pilha {
int topo;
int capa;
float *pElem;
};
void criarpilha( struct Pilha *p, int c ){
p->topo = -1;
p->capa = c;
p->pElem = (float*) malloc (c * sizeof(float));
}
void push ( struct Pilha *p, float v){
p->topo++;
p->pElem [p->topo] = v;
}
float sub(struct Pilha *p)
{
int x,y;
float calc;
p->topo--;
x=p->pElem [p->topo];
p->topo++;
y=p->pElem [p->topo];
calc=x-y;
p->topo--;
p->pElem [p->topo]=calc;
return calc;
}
float mpy(struct Pilha *p)
{
int x,y;
float calc;
p->topo--;
x=p->pElem [p->topo];
p->topo++;
y=p->pElem [p->topo];
calc=x*y;
p->topo--;
p->pElem [p->topo]=calc;
return calc;
}
float add(struct Pilha *p)
{
int x,y;
float calc;
p->topo--;
x=p->pElem [p->topo];
p->topo++;
y=p->pElem [p->topo];
calc=x+y;
p->topo--;
p->pElem [p->topo]=calc;
return calc;
}
float Div(struct Pilha *p)
{
int x,y;
float calc;
p->topo--;
x=p->pElem [p->topo];
p->topo++;
y=p->pElem [p->topo];
calc=x/y;
p->topo--;
p->pElem [p->topo]=calc;
return calc;
}
float dec(struct Pilha *p)
{
int x;
x=p->pElem [p->topo];
x--;
return x;
}
float pop ( struct Pilha *p ){
float aux = p->pElem [p->topo];
p->topo--;
return aux;
}
float monstrarpilha ( struct Pilha *p ){
return p->pElem [p->topo];
}
int main(){
struct Pilha p;
int capacidade=4;
float valor;
int A=9,B=3,C=2,D=1,E=1;
criarpilha (&p, capacidade);
push(&p,A);
printf("\nPUSH A: %.1f\n",monstrarpilha(&p));
push(&p,B);
printf("\nPUSH B: %.1f\n",monstrarpilha(&p));
sub(&p);
printf("\nSubtracao: %.1f\n",sub(&p));
push(&p,C);
printf("\nPUSH C: %.1f\n",monstrarpilha(&p));
push(&p,D);
printf("\nPUSH D: %.1f\n",monstrarpilha(&p));
push(&p,E);
printf("\nPUSH E: %.1f\n",monstrarpilha(&p));
mpy(&p);
printf("\nmultiplicacao: %.1f\n",mpy(&p));
add(&p);
printf("\nadicao: %.1f\n",add(&p));
dec(&p);
printf("\ndecrementar: %.1f\n",dec(&p));
Div(&p);
printf("\ndivisao: %.1f\n",Div(&p));
printf("\nPOP F%.1f\n",pop(&p));
}