?? expevaluation.c
字號:
#include <stdio.h>#include <math.h>#include <string.h>#include <stdlib.h>#include "stack.c"#include "stackdouble.c"#define Max 100 /* operand's longest digit */#define TRUE 1#define FALSE 0 #define NUMOFOPR 7 /* Number of operator */static char OPS[NUMOFOPR]={'+','-','*','/','(',')','#'};static char order[NUMOFOPR][NUMOFOPR]={{'>','>','<','<','<','>','>'},{'>','>','<','<','<','>','>'},{'>','>','>','>','<','>','>'},{'>','>','>','>','<','>','>'},{'<','<','<','<','<','=',' '},{'>','>','>','>',' ','>','>'},{'<','<','<','<','<',' ','='}};float Execute(float a,char op, float b){ float c; switch(op){ case '+': c=a+b; break; case '-': c=a-b; break; case '*': c=1.0*a*b; break; case '/': c=(1.0*a)/b; break; } return c;}float Getnumber (char *a){ int n; /* n digits*/ int i; int point; /* float point location */ float c; n = strlen(a); if (a[0]=='.') return ; if (a[n-1]=='.') return ; point = n; for(i=1; i<n ; i++) if(a[i]=='.') point = i; c=0.0; for(i=0; i< point; i++) c += (a[i]-48)* pow(10,(point-i-1)); for(i=point+1 ; i< n; i++) c += (a[i]-48)* pow(10,(point-i)); return c;}int In( char ch, char *OPS){ int i; int flag=0; for (i=0;i< NUMOFOPR ;i++) if (ch==OPS[i]){ return (TRUE); flag=1; } if (flag==0) return (FALSE);}char Compare( char x1,char x2 ){ int i; int m,n; m=6; n=5; /* to prevent array overflow */ for(i=0;i<NUMOFOPR;i++){ if(x1==OPS[i]) m = i; if(x2==OPS[i]) n = i; } return order[m][n];}int main(){ seqstack1 operand; seqstack operator; char ch[Max]; char *num; /* dynamic storage allocation */ char x,op; int n,i,m; int first,last; float a,b,c,v; Initstack1(&operand); Initstack(&operator); Push(&operator,'#'); printf("\n\nPlease input an expression (Ending with #): "); scanf("%s",ch); n = strlen(ch); v=0.0; for (i=0; i<n ; i++){ if(ch[i] !='#'|| Gettop(&operator)!='#'){ if(! In(ch[i],OPS) ){ first = i; /* record the number of first digit number */ last = first ; /* record the number of last digit number */ while( !In(ch[last+1],OPS) ) last++; num = (char *)malloc(sizeof(char)*(last-first+1)); for(m=0,i=first;i<last+1;m++,i++) num[m]=ch[i]; a = Getnumber(num); /*用ch逐個掃面各位數(shù)碼,并轉(zhuǎn)換為十進(jìn)制數(shù)a*/ Push1(&operand,a); free(num); i=last; }/* if */ else switch (Compare(Gettop(&operator),ch[i])){ case '<': Push(&operator,ch[i]); break; case '=': Pop(&operator,&x); break; case '>': Pop(&operator,&op); Pop1(&operand,&b); Pop1(&operand,&c); v= Execute(c,op,b); /*對a和b進(jìn)行op運(yùn)算*/ Push1(&operand,v); printf("%f\n",v); i--; break; default: printf(" Wrong operator !\n"); break; }/* switch */ }/*if*/ else break; }/* for */ v = Gettop1(&operand); printf("%f,%d\n",v,n);}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -