首页 > 代码库 > 逆波兰计算器
逆波兰计算器
#include <stdio.h>#include <stdlib.h>#include <ctype.h>#include <math.h>#define IncreSize 10#define InitSize 10typedef int status;typedef int Elemtype;typedef struct sStack{ Elemtype *base; Elemtype *top; int StackSize;}sqStack;void InitStack(sqStack *s){ s->base = (Elemtype *)malloc(sizeof(int)*InitSize); if(!s->base) exit(0); else { s->top = s->base; s->StackSize = InitSize; //return OK; }}void Push(sqStack *s, Elemtype e){ if(s->top - s->base >= s->StackSize) { s->base = (Elemtype *)realloc(s->base,(s->StackSize + IncreSize)*sizeof(Elemtype)); //这里申请的大一些的空间; if(!s->base) exit (0); } *(s->top) = e; s->top++; //return OK;}void Pop(sqStack *s, Elemtype *e){ if(s->top == s->base) exit(0); *e = *--(s->top); // return OK;}int StackLen(sqStack s){ return(s.top - s.base); //注意这里的结果是栈中的数据个数;}//输入数字,然后根据计算法则进行求解。int main(){ char c; char str[20]; //设立一个缓冲区; int i = 0; int d,e,f; sqStack s; InitStack(&s); scanf("%c", &c); while(c != ‘#‘) { while( isdigit(c) || c == ‘.‘) { str[i++] = c; str[i] = ‘\0‘; if(i >= 10) { printf("过界\n"); return -1; } scanf("%c", &c); if(c == ‘ ‘) { d = atof(str); Push(&s,d); i = 0; break; } } switch(c) { case ‘+‘ : Pop(&s, &e); Pop(&s, &f); Push(&s,e+f); break; case ‘-‘: Pop(&s, &e); Pop(&s, &f); Push(&s,f-e); break; case ‘*‘: Pop(&s, &e); Pop(&s, &f); Push(&s,e*f); break; case ‘/‘: Pop(&s, &e); Pop(&s, &f); if(f == 0) exit(0); Push(&s,e/f); break; } scanf("%c",&c); } Pop(&s,&e); printf("%d",e); return 0;}
这个程序还是有些地方刚刚开始细节没有考虑清楚。
逆波兰计算器
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。