用键盘输入一个表达式,求出结果.(里面可以有括号,运算符为三个)
例:(1+2)*3-5
算出它的结果.望大哥们给出源码,谢谢!
[此贴子已经被作者于2004-08-23 00:13:55编辑过]
#include <math.h> #include <stdio.h> #define MAX 100 /*四则运算程序,本程序用分数计算思想,给出分数和小数两种解*/ typedef struct num{long n1;long n2;}num; /*本程序定义的分数数据类型,n1为分子,n2为分母*/
typedef struct stack{int top;num data[MAX];}stack;stack *table2,*table1;/*栈的结构*/
void max(num *s) /*约分函数*/ {long a=s->n1,b=s->n2; long ma; long mi;long t; a=abs(a);b=abs(b); if(a>b){ma=a;mi=b;} else {ma=b;mi=a;} if(a){ for(t=mi;t>1;t--) {if((mi%t==0)&&(ma%t==0))break; } s->n1=(s->n1/t)*(s->n2/t)/abs(s->n2/t);s->n2=abs(s->n2/t);}}
stack *creat() /*创建一个空栈*/ { stack *head; head=(stack*)malloc(sizeof(stack));head->top=0;if(!head)printf("wrong"); return head;}
int push(stack *head,num *n) /*进栈函数*/ {if(head->top==MAX)return 0; else {head->data[head->top].n1=n->n1;head->data[head->top].n2=n->n2;head->top++;} return 1;}
num *pop(stack *head) /*出栈函数*/ {if(head->top==0)printf("error11"); else {head->top--;return &head->data[head->top];}}
void destory(stack *head) /*销毁一个栈*/ {free(head);}
num *get(stack *head){return &head->data[head->top-1];} /*返回栈顶元素*/
int empty(stack *head){if(head->top==0)return 1;else return 0;} /*判断栈是否为空*/
num *oprate(num *a,num *b,num *e) /*oprate()为计算函数,用于分数计算 */ {num *s=(num*)malloc(sizeof(num));long e2=e->n1,d=b->n1; if(e2=='+'){s->n1=(a->n1)*(b->n2)+(a->n2)*(b->n1);s->n2=(a->n2)*(b->n2);max(s);} if(e2=='-'){s->n1=(a->n1)*(b->n2)-(a->n2)*(b->n1);s->n2=(a->n2)*(b->n2);max(s);} if(e2=='*'){s->n1=(a->n1)*(b->n1);s->n2=(a->n2)*(b->n2);max(s);} if(e2=='/'){s->n1=(a->n1)*(b->n2);s->n2=(a->n2)*(b->n1);max(s); } return s;}
void put() {num *a,*b,*e; if(get(table1)->n1=='*'||get(table1)->n1=='/') {a=pop(table2);b=pop(table2);e=pop(table1);a=oprate(b,a,e); push(table2,a);put();} }
main(){char data[100];int i,j=0;num a[100],*answer,*x1,*x2,*e,*ss;float an,a1,a2; printf("请输入算式,按回车结束:\n"); gets(data); for(i=0;data[i-1]!='\0';i++)printf("%c",data[i]);printf("="); table1=creat(); table2=creat(); for(i=0;data[i-1]!='\0';i++){if(data[i]>='0'&&data[i]<='9'){a[j].n1=10*a[j].n1+data[i]-'0';a[j].n2=1; } else {if(i)j++;a[j].n1=data[i];a[j].n2=0; if(data[i+1]>='0'&&data[i+1]<='9')j++;}} /*从新组合*/
for(i=0;i<j;i++) {if(!a[i].n2){ push(table1,&a[i]); if(get(table1)->n1==')'){pop(table1); while(get(table1)->n1!='('){x1=pop(table2);x2=pop(table2);e=pop(table1);x1=oprate(x2,x1,e); push(table2,x1);}/*while*/pop(table1);put();}}/*if*/ else{ push(table2,&a[i]);put(); }/*else*/}/*for*/ while(!empty(table1)&&!empty(table2)) {x1=pop(table2);x2=pop(table2);e=pop(table1);x1=oprate(x2,x1,e); push(table2,x1);} answer=pop(table2);a1=answer->n1;a2=answer->n2;an=a1/a2; if(answer->n2==1){printf("%ld",answer->n1);getch();}
else { printf("%ld/%ld=%f",answer->n1,answer->n2,an);getch();} }
[此贴子已经被作者于2004-08-25 08:48:05编辑过]