C语言-C语言程序设计-Application-逆波兰计算器

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

C语⾔-C语⾔程序设计-Application-逆波兰计算器C语⾔-C语⾔程序设计-Application-逆波兰计算器
最近软考的时候才知道的逆波兰表达式,这个竟然是C的内容之⼀,把书上的抄下来了。

主要就是对操作数的⼊栈出栈,以及与操作符匹配的⼀种应⽤⽅式。

#include <stdio.h>
#include <stdlib.h> /* 为了使⽤atof函数*/
#define MAXOP 100 /* 操作数或运算符的最⼤长度*/
#define NUMBER '0' /* 标识找到⼀个数*/
int getop(char []);
void push(double);
double pop(void);
/* 逆波兰计算器*/
int main()
{
int type;
double op2;
char s[MAXOP];
while((type = getop(s)) != EOF){
switch(type){
case NUMBER:{
push(atof(s));
break;
};
case '+':{
push(pop() + pop());
break;
};
case '*':{
push(pop() * pop());
break;
};
case '-':{
op2 = pop();
push(pop() - op2);
break;
};
case '/':{
op2 = pop();
if(op2 != 0.0)
push(pop() / op2);
else
printf("error: zero divisor\n");
break;
};
case '%':{ //取余,负数有什么问题吗?
op2 = pop();
double op1 = pop();
op1 = (int)op1 % (int)op2;
push(op1);
break;
}
case '\n':{
printf("\t%.8lf\n",pop());
break;
};
default:
printf("error: unknown command %s \n", s);
break;
}
}
return 0;
}
#define MAXVAL 100 /* 栈val的最⼤深度*/
int sp = 0; /* 下⼀个空闲栈位置*/
double val[MAXVAL]; /* 值栈*/
/* push函数: 把f压⼊到值栈中 */
void push(double f){
if(sp < MAXVAL)
val[sp++] = f;
else
printf("error: stack full, can't push %lf\n", f); }
/* pop函数:弹出并返回栈顶的值 */
double pop(void){
if(sp > 0)
return val[--sp];
else{
printf("error: stack empty\n");
return 0.0;
}
}
#include <ctype.h>
int getch(void);
void ungetch(int);
/*getop函数:获取下⼀个运算符或数值操作符*/ int getop(char s[]){
int i, c;
while ((s[0] = c = getch()) == ' ' || c == '\t');
s[1] = '\0';
if(!isdigit(c) && c != '.')
return c; /*不是数*/
i = 0;
if(isdigit(c)) /* 收集整数部分*/
while(isdigit(s[++i] = c = getch()));
if(c == '.') /* 收集⼩数部分*/
while(isdigit(s[++i] = c = getch()));
s[i] = '\0';
if(c != EOF)
ungetch(c);
return NUMBER;
}
#define BUFSIZE 100
char buf[BUFSIZE]; /* ⽤于ungetch函数的缓冲区*/ int bufp = 0; /* buf中下⼀个空闲位置*/
int getch(void){ /* 取⼀个字符(可能是压回字符)*/ return (bufp > 0)? buf[--bufp]:getchar();
}
void ungetch(int c){ /* 把字符压回到输⼊中*/
if(bufp >= BUFSIZE)
printf("ungetch: too many characters\n");
else
buf[bufp++] = c;
}。

相关文档
最新文档