スタック自体(istack.hとistack.c)と、入力された普通の数式(2+5*8-4/5など)をRPNに変換するものは大学の講義ページのコード例の引用で、rpn.c内の計算処理の部分を作っています。
環境はWin10でVS2017付属のコンパイラを使っています。
現在、2+5+3*5+4を計算しようとすると、出力が50になってしまいます。
計算処理のどこかが間違っているのだとは思うのですが…
istack.h
// istack.h --- int type stack interface
#include <stdbool.h>
struct istack;
typedef struct istack *istackp;
istackp istack_new(int size); // allocate new stack
bool istack_isempty(istackp p); // test if the stack is empty
void istack_push(istackp p, int v); // push a value
int istack_pop(istackp p); // pop a value and return it
int istack_top(istackp p); // peek the topmost value
// istack.c --- int type stack impl. with array
#include <stdlib.h>
#include "istack.h"
struct istack { int ptr; int *arr; };
istackp istack_new(int size) {
istackp p = (istackp)malloc(sizeof(struct istack));
p->ptr = 0; p->arr = (int*)malloc(size * sizeof(int));
return p;
}
bool istack_isempty(istackp p) { return p->ptr <= 0; }
void istack_push(istackp p, int v) { p->arr[p->ptr++] = v; }
int istack_pop(istackp p) { return p->arr[--(p->ptr)]; }
int istack_top(istackp p) { return p->arr[p->ptr - 1]; }
//RPN
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include "istack.c"
int operprec(int c) {
switch(c) {
case '+': case '-': return 1;
case '*': case '/': case '%': return 2;
case '^': return 3;
default: return 0;
}
}
int main(void) {
istackp s = istack_new(200);
istackp t = istack_new(200);
int c, d;
printf("s> ");
for(c = getchar(); c != '\n' && c != EOF; c = getchar()) {
if(isdigit(c)) {
istack_push(t, c);
putchar(c);
continue;
}
while(!istack_isempty(s) && operprec(istack_top(s)) >= operprec(c)) {
d = istack_pop(s);
istack_push(t ,d);
putchar(d);
}
istack_push(s, c);
}
while(!istack_isempty(s)) {
d = istack_pop(s);
istack_push(t ,d);
putchar(d);
}
//ここから計算のプログラム
int num, tmp;
while(!istack_isempty(t)) {
num = istack_pop(t);
if(isdigit(num)) {
istack_push(s, (int)num);
continue;
} else {
switch(num) {
case '+':
istack_push(s, istack_pop(s)+istack_pop(s));
break;
case '*':
istack_push(s, istack_pop(s)*istack_pop(s));
break;
case '-':
tmp = istack_pop(s);
istack_push(s, istack_pop(s)-tmp);
break;
case '/':
tmp = istack_pop(s);
istack_push(s, istack_pop(s)/tmp);
break;
case '%':
tmp = istack_pop(s);
istack_push(s, istack_pop(s)%tmp);
break;
case '^':
tmp = istack_pop(s);
istack_push(s, istack_pop(s)^tmp);
break;
}
}
}
/*while(!istack_isempty(s)) {
putchar(istack_pop(s));
}*/
printf(" = %d", istack_pop(s));
putchar('\n');
return 0;
}
s> 2+5+3*5+4
25+35*+4+ = 50
のようになってしまいます。
間違いの箇所と理由などを教えていただけたらと思います。
よろしくお願いします。