栈 实现四则运算的计算器

来源:互联网 发布:土豆视频windows客户端 编辑:程序博客网 时间:2024/05/23 11:00

  这几天一直在做停车场和计算器项目,在停车场做完后,再去做计算器,突然发现简单了很多,对大体的一个思路有了很清楚的了解,与停车场相比,计算器只用了一个结构变量,只有一个操作数栈和一个运算符栈,而停车场用了一个停车栈、一个让车栈和一个候车队列。因此,只要将计算器的算法理清后,写起来是挺简单的。

/**********************************************************File Name:         Author:          xxx     Date:2016-12-16Description:   实现计算器功能Fuction List:************************************************************/#include <stdio.h>#define SIZE      100#define ok          0#define error      -1typedef struct{int data[SIZE];int top;}DATA;//初始化int Init(DATA *p){if(p == NULL){return error;}p->top = -1;return ok;}//判断空栈int Empty(DATA *p){if(p == NULL){return error;}return p->top == -1;}//判断满栈int Full(DATA *p){if(p == NULL){return error;}return p->top == SIZE - 1;}//压栈int Push(DATA *p,int data){if(p == NULL){return error;}if(Full(p) != ok){return error;}p->top++;p->data[p->top] = data;return ok;}//出栈int Pop(DATA *p){if(p == NULL){return error;}if(Empty(p) != ok){return error;}int data;data = p->data[p->top];p->top--;return data;}//获取栈顶元素int Getpop(DATA *p){if(p == NULL){return error;}if(Empty(p) != ok){return error;}return p->data[p->top];}//判断优先级int judge(char ch){switch (ch){case '(' :{return 3;}case '*' :{return 2;}case '/' :{return 2;}case '+' :{return 1;}case '-' :{return 1;}default :{return error;}}}int main(){char a[SIZE] = {0};int i = 0;int temp = 0;int j;DATA num;if(Init(&num) != ok){return error;}DATA opt;if(Init(&opt) != ok){return error;}if ((Init(&num) && Init(&opt)) != ok){return error;}printf("please input:\n");scanf("%s",a);while(a[i] != '\0' || Empty(&opt) != 1){if(a[i] >= '0' && a[i] <= '9'){temp = temp * 10 + a[i] - '0';         i++;if(a[i] < '0' || a[i] > '9'){Push(&num,temp);temp = 0;}}else{if((a[i] != '\0' && Empty(&opt)) || (a[i] != ')' && Getpop(&opt) == '(') || (judge(a[i]) > judge(Getpop(&opt)))){Push(&opt,a[i]);         i++;continue;}if(a[i] == ')' && Getpop(&opt) == '('){Pop(&opt);i++;continue;}if(a[i] == '\0' || a[i] == ')' || judge(a[i]) <= judge(Getpop(&opt))){switch (Pop(&opt)){case '*' :{Push(&num,Pop(&num)*Pop(&num));break;}case '/':{j = Pop(&num);Push(&num,Pop(&num)/j);break;}case '+':{Push(&num,Pop(&num)+Pop(&num));break;}case '-':{j = Pop(&num);Push(&num,Pop(&num)-j);break;}default:{break;}}continue;}}}printf("\n%s = %d\n",a,Pop(&num));return 0;}


1 0