C++有关“表达式计算”的内容,写一个用于表达式计算的C程序

1个回答

  • 算法可以用入栈、出栈来进行,对符号的优先级进行比较.然后计算.求幂一般用得少,现给代码增加了一个.运算的结果应在整数的范围内.代码在VC6.0下运行通过.#include

    #include

    #include

    #define null 0struct shuju{int a;struct shuju *next;}*x1,*head1,*current1;struct caozuo{char b;struct caozuo *next;}*x2,*head2,*current2;void push1(int a1){x1=(struct shuju *)malloc(sizeof(struct shuju));x1->a=a1;x1->next=null;x1->next=head1->next;head1->next=x1;}void push2(char b1){x2=(struct caozuo *)malloc(sizeof(struct caozuo));x2->b=b1;x2->next=null;x2->next=head2->next;head2->next=x2;}char pop1(){int t;if(head1->next==null){printf("The linked list is empty!n");return 0;}else{current1=head1->next;head1->next=current1->next;t = current1->a;free(current1);/*应先释放*/return(t);}}char pop2(){char t;if(head2->next==null){printf("The linked list is empty!n");return 0;}else{current2=head2->next;head2->next=current2->next;t = current2->b;free(current2);/*应先释放*/return(t);}}int gettop1(){if(head1->next) return(head1->next->a);return 0;}char gettop2(){if(head2->next)return(head2->next->b);return 0;}int operate(int a,char theta,int b){int c=a;switch(theta){case '+':c=a+b;break;case '-':c=a-b;break;case '*':c=a*b;break;case '/':c=a/b;break;case '^':if(b==0)c=1;else if(b==1) c=a; else while(--b) c*=a; break;}return c;}void getcmd(int *value,char * c)//读取一个数值,或是一个命令{int v=0;char ch;while(1){ch=getchar();if(ch>='0' ch<='9'){v = v*10+(ch-'0');}else{ *c = ch; break;}};*value = v;}char precede(char a,char b){if((a==')'&&b=='(')||(a=='#'&&b=='#'))return '=';else if(a=='('||b=='#'||b=='(') return '>';else if(a=='^') return '>';else if((a=='*'||a=='/') (b=='+'||b=='-')) return '>';return 'push2('#');inta;char c; char t; /*操作符优先级*/getcmd(&a,&c);while(1)/*如果输入的和栈底都是'#',则完成*/{if(c=='#' gettop2()=='#') break;if(!(c=='+'||c=='-'||c=='*'||c=='/'||c=='('||c==')'||c=='#'||c=='^')){if(a!=0)push1(a);getcmd(&a,&c);}else if(a!=0){push1(a);a = 0;}else{/*判断输入的操作符,与栈顶操作符比较*/t = precede(c,gettop2());switch(t){int a1,b1;/*计算用数值*/case '>':/*如果大于栈顶,操作数入栈*/push2(c);getcmd(&a,&c);/*读下一个*/break;case '=':pop2();/*弹出'('或'#'*/getcmd(&a,&c);/*读下一个*/break; case 'b1=pop1();a1=pop1();push1(operate(a1,pop2(),b1));if(c!='#'&&c!=')')/*没有输入完成,则入栈操作符*/{push2(c);getcmd(&a,&c);/*读下一个字符*/}break;}}};return gettop1();}void main(){head1=(struct shuju *)malloc(sizeof(struct shuju));head1->next=null;head2=(struct caozuo *)malloc(sizeof(struct caozuo));head2->next=null;printf("n算数表达式的结果为:%dn",qiuzhi());}例:输入:2*3+6/2-(3-1)+2*(6-4)+2^(2+1)#输出:19