C语言 实现四则运算简单计算器

来源:互联网 发布:东华云计算有限公司 编辑:程序博客网 时间:2024/05/05 10:48

用C语言编写了一个简单的四则运算计算器,输入以#号结束

#include<stdio.h>#include<stdlib.h>#define MAXSIZE 100#define OKAY 1#define ERROR 0 char ops[7]={'+','-','*','/','(',')','#'};int cmp[7][7]={{2,2,1,1,1,2,2},{2,2,1,1,1,2,2},{2,2,2,2,1,2,2},{2,2,2,2,1,2,2},{1,1,1,1,1,3,0},{2,2,2,2,0,2,2},{1,1,1,1,1,0,3},};typedef struct {char op[101];int top;}Stack1;typedef struct {int num[100];int top;}Stack2;Stack1 *s1;Stack2 *s2;int InitStack1(Stack1 *s){if(!s){return ERROR;}s->top=-1;return OKAY;}int InitStack2(Stack2 *s){if(!s){return ERROR;}s->top=-1;return OKAY;}int pushStack1(Stack1 *s ,char c){if(s->top==MAXSIZE-1){return ERROR;}s->top++;s->op[s->top]=c;return OKAY; }int pushStack2(Stack2 *s,double n){if(s->top==MAXSIZE-1){return ERROR;}s->top++;s->num[s->top]=n;return OKAY; }int isEmpty1(Stack1 *s){return ((s->top==-1)?ERROR:OKAY);}int isEmpty2(Stack2 *s){return((s->top==-1)?ERROR:OKAY);}char popStack1(Stack1 *s,char c){if(s->top==-1){printf("运算符栈为空!\n");return ERROR;}c=s->op[s->top];s->top--;return c;}int popStack2(Stack2 *s,int n){if(s->top==-1){printf("操作数栈为空!\n");return ERROR;}n=s->num[s->top];s->top--;return n;}char getTop1(Stack1 *s){if(s->top==-1){printf("运算符栈为空!\n");return ERROR;}return (s->op[s->top]);}int getTop2(Stack2 *s){if(s->top==-1){printf("运算符栈为空!\n");return ERROR;}return (s->num[s->top]);}char compare(char op1,char op2){int i,m,n;int priority;char pri;for(i=0;i<7;i++){if(op1==ops[i]){m=i;}if(op2==ops[i]){n=i;}}priority=cmp[m][n];switch(priority){case 1:pri='<';break;case 2:pri='>';break;case 3:pri='=';break;case 0:pri='$';printf("表达式错误!");break; }return pri;}/*计算函数 */int compute(int a,char op,int b){int result;switch(op){case '+':result=a+b;break;case '-':result=a-b;break;case '*':result=a*b;break;case '/':result=a/b;break;}return result;} int main(){int a=0;int b=0;int temp=0,sum=0;char op,ch;Stack1 *s1;Stack2 *s2;s1=(Stack1*)malloc(sizeof(Stack1));s2=(Stack2*)malloc(sizeof(Stack2));InitStack1(s1);//printf("1");InitStack2(s2);//printf("2")char *str=(char*)malloc(100);//使用指针字符串pushStack1(s1,'#');printf("Please input a str:\n");gets(str);ch=*str++;//printf("%c",ch);while(ch!='#' || getTop1(s1)!='#'){if(ch>='0' && ch<='9'){temp=ch-'0';ch=*str++;while(ch>='0' && ch<='9'){temp=temp*10+ch-'0';ch=*str++;}printf("temp:%d\n",temp);pushStack2(s2,temp);}else{switch(compare(getTop1(s1),ch)){//printf("pop %d\n",popStack2(s2,))                case'<':     pushStack1(s1,ch); ch=*str++; break;case'=':     popStack1(s1,op); ch=*str++; break;     case'>':      op=popStack1(s1,op);      b=popStack2(s2,b);          a=popStack2(s2,a);      sum=compute(a,op,b);          pushStack2(s2,sum);            break;  }}}printf("%d",getTop2(s2)); }


0 0
原创粉丝点击