源码空间也这个控件,但我现在不记得在什么位置了.
我有个C语言的代码:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define POW 1
#define MUL 2
#define DIV 3
#define ADD 4
#define SUB 5
#define Lp 6
#define Rp 7
#define END 8
#define Epsilon 1e-7
typedef double NODE;
struct{
char op;
int code;
}opchTbl[]={{'*',2},{'/',3},{'+',4},{'-',5},{'(',6},{')',7},{'^',1},{'/n',8},{' ',-1}};
typedef struct node{
NODE data;
struct node *link;
}LNODE;
LNODE * optop,*numtop;
/*进栈函数*/
void l_push(NODE x,LNODE **toppt)
{LNODE *p=(LNODE *)malloc(sizeof(LNODE));
p->data=x;
p->link=*toppt;
*toppt=p;
}
/*出栈函数*/
int l_pop(NODE *cp,LNODE **toppt)
{
LNODE *p=*toppt;
if(*toppt==NULL)return 1;
*cp=p->data;
*toppt=p->link;
free(p);
return 0;
}
int osp[]={5,3,3,2,2,5,1,1},isp[]={4,3,3,2,2,0};
void synError()
{
double temp;
printf("表达式句法出错!");
while(optop!=NULL)
l_pop(&temp,&optop);
while(numtop!=NULL)
l_pop(&temp,&numtop);
exit(0);
}
double eval(char tag,double left,double right)
{
int n;
double result;
switch(tag)
{
case POW:for(n=1,result=left;n<right;n++)
result *=left;
return result;
case ADD: return left+right;
case SUB: return left - right;
case MUL: return left * right;
case DIV: if (fabs(right)<Epsilon){
printf("除0出错!/n");
exit(1);
}
return left/right;
}
printf("表达式有错!/n");
return 1.0;
}
int c=' ';
#define RADIX 10
int getToken(double *nump)
{
double dradix,num;
int i;
while(c==' '||c=='/t')c=getchar();
if(c<'0'||c>'9')
{
for(i=0;opchTbl.code!=-1 && opchTbl.op!=c;i++);
if (opchTbl.code==-1) synError();
if (c!='/n') c=getchar();
return opchTbl.code;
}
num=0.0;
while(c>='0' && c<='9')
{
num=RADIX*num+c-'0';
c=getchar();
}
if(c=='.')
{dradix=1.0/RADIX;
c=getchar();
while (c>='0' && c<='9')
{
num=num+(c-'0')*dradix;
dradix/=RADIX;
c=getchar();
}
}
*nump=num;
return 0;
}
void main()
{
double num,dop,operand1,operand2,res;
int type;
char ans,op;
do
{printf("请输入表达式!/n");
optop=numtop=NULL;//清空栈
l_push(Lp,&optop);//'('进符号栈
do c=getchar();
while(c==' '||c=='/n',c=='/t');
while(1)
{
type=getToken(&num);
if(type==0) //是数字
l_push(num,&numtop);//数字进栈
else{
if(osp[type-1]>isp[(int)optop->data-1])//栈外高,进栈
l_push((double)type,&optop);
else{//栈内高
while(osp[type-1]<=isp[(int)optop->data-1] && optop->data<=5)
{if(l_pop(&dop,&optop))
synError();
op=(char)dop;
if(l_pop(&operand2,&numtop))
synError();
if(l_pop(&operand1,&numtop))
synError();
res=eval(op,operand1,operand2);
l_push(res,&numtop);
}
if(type==END)break;
if(type==Rp){
do if (l_pop(&dop,&optop))
synError();
while ((char)dop!=Lp);
}
else
l_push((double)type,&optop);
}
}
}
if(l_pop(&operand1,&numtop)) synError();
while(optop!=NULL) l_pop(&dop,&optop);
while(numtop!=NULL) l_pop(&res,&numtop);
printf("结果为:%f/n",operand1);
printf("继续吗?");
scanf("%c",&ans);
}
while(ans=='y'||ans=='Y');
}