數學表達式計算器
1+2/3*(4-6)*6/8+9*2 = ?
#include <stdio.h>include <stdlib.h>
define MAXSIZE 32
typedef struct{ int data[MAXSIZE];//數據段 int top;//棧指針 }sqstack;
sqstack sqstack_create() { sqstack sq; sq = malloc(sizeof(*sq)); if(sq == NULL ) { return NULL; } sq->top = -1; return sq; }
int sqstack_push(sqstack sq, int data)//入棧 { if(sq->top == MAXSIZE-1)//full { return -1; } else { sq->data[++sq->top] = *data; } return 0; }
int sqstack_top(sqstack sq, int data)//取得棧頂數據 { if(sq->top == -1)//empty { return -1; } *data = sq->data[sq->top]; return 0; }
int sqstack_pop(sqstack sq, int data)//出棧 { if(sq->top == -1)//empty { return -1; } *data = sq->data[sq->top--]; return 0; }
int compute(sqstack snum, int ope) { int n1, n2, n; sqstack_pop(snum, &n1); sqstack_pop(snum, &n2); switch(ope) { case '+': n=n1+n2; printf("%d+%d=%d\n", n1, n2, n); break; case '-': n=n2-n1; printf("%d-%d=%d\n", n2, n1, n);break; case '': n=n1n2; printf("%d%d=%d\n", n1, n2, n);break; case '/': n=n2/n1; printf("%d/%d=%d\n", n2, n1, n);break; default: return -1;//break; } sqstack_push(snum, &n);//將運算結果壓入數字棧 return 0; }
void deal_bracket(sqstack snum, sqstack sope)//處理括號 { int old_ope; sqstack_top(sope, &old_ope);//取得棧頂運算符 while(old_ope != '(') { sqstack_pop(sope, &old_ope); compute(snum, old_ope); sqstack_top(sope, &old_ope);//取得棧頂運算符 } sqstack_pop(sope, &old_ope); }
int sqstack_is_empty(sqstack *sq) { return (sq->top == -1); }
int get_pri(int ope) { switch(ope) { case '(': return 0; case '+': case '-': return 1; case '': case '/': return 2; } } void deal_ope(sqstack snum, sqstack sope, int ope)//處理運算符 { int old_ope; if(ope == '('||sqstack_is_empty(sope)) { sqstack_push(sope, &ope); return ; } sqstack_top(sope, &old_ope); if(get_pri(ope) > get_pri(old_ope)) { sqstack_push(sope, &ope); return ; } while(get_pri(ope) <= get_pri(old_ope))// + { sqstack_pop(sope,&old_ope); compute(snum,old_ope); if(sqstack_is_empty(sope)) break; sqstack_top(sope,&old_ope); } sqstack_push(sope,&ope); }
int main() { sqstack snum;//運算數字棧 sqstack sope;//運算符棧 int i = 0, value = 0, flag = 0, old_ope;
char str[] = "1+3-(2*5)*(8-6)+5";//所要計算的表達式 //初始化 snum = sqstack_create(); sope = sqstack_create(); while(str[i] != '\0') { if(str[i] >= '0' && str[i] <= '9')//數字 { value = value*10 + str[i]-'0'; flag = 1; } else//運算符 { if(flag == 1)//取得了運算的數字 { sqstack_push(snum, &value);//數字入 運算數字棧 value = 0; flag = 0; } if(str[i] == ')') { deal_bracket(snum,sope); } else//(+-*/ { deal_ope(snum,sope,str[i]); } } i++; } if(flag) { sqstack_push(snum,&value); } while(!sqstack_is_empty(sope)) { sqstack_pop(sope, &old_ope); compute(snum, old_ope); } sqstack_pop(snum, &value); printf("%s = %d\n", str, value); return 0;
}</pre>