1 Star 0 Fork 0

赵子豪 / The-C-Programming-Language

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
use a stack to make a computer machine.c 2.12 KB
一键复制 编辑 原始数据 按行查看 历史
#include <stdio.h>
#include <stdlib.h> /* 为了使用atof()函数 */
#define MAXOP 100 /* 操作数或运算符的最大长度 */
#define NUMBER '0' /* 标志找到一个数 */
int gettop(char []);
void push(double);
double pop(void);
/* 逆波兰计算器 */
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 '\n':
printf("\t0.8g\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 %g\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()))
;
s[i] = '\0';
if (c != EOF)
ungetch(c);
return NUMBER;
}
/* getch()及ungetch()函数的另类写法 */
/*
#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;
}
*/
C
1
https://gitee.com/zhao_zihao/The-C-Programming-Language.git
git@gitee.com:zhao_zihao/The-C-Programming-Language.git
zhao_zihao
The-C-Programming-Language
The-C-Programming-Language
The-C-Programming-Language

搜索帮助