练习4-6 给计算机程序增加处理变量的命令(提供26个具有单个英文字母变量名的变量很容易)。增加一个变量存放最近打印的值。
主函数:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "calc.h"
#define MAXLEN 100
#define MAXOP 100
int getop(char []);
void push(double);
double pop(void);
void math_op(char s[]);
void mod(void);
int main()
{
int type;
double op1, op2;
char s[MAXOP];
double val[26];
double recent_val;
while ((type = getop(s)) != EOF)
{
switch (type) {
case NUMBER:
push(atof(s)); //printf("push number\n");
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 divisior\n");
break;
case '%':
mod();
break;
case MATHOP: //判断是否是math.h中函数
math_op(s);
break;
case VARIABLE:
val[s[0] - 'a'] = pop();
push(val[s[0] - 'a']);
break;
case '\n':
recent_val = pop();
printf("result: %.8g\n", recent_val);
break;
default:
printf("error: unknown command %s\n", s);
break;
}
}
return 0;
}
void mod(void)
{
double op1, op2;
op2 = pop();
if ((op1 = pop()) <= 0.0)
{
printf("error:mod num lower than zero\n");
return;
}
else
{
printf("%g %g\n", op1, op2);
printf("%.1lf %.1lf %g %g \n",floor(op1 + 0.5), floor(op2 + 0.5), op1, op2);
if (floor(op1 + 0.5) != op1 || floor(op2 + 0.5) != op2)
{
printf("error: not integer\n");
return;
}
if (op2 < 0.0)
{
while (op2 < 0.0)
op2 += op1;
push((int)op1 % (int)op2);
return;
}
else
push((int)op1 %(int)op2);
return;
}
}
void math_op(char s[])
{
if (!strcmp(s, "sin"))
{
push(sin(pop()));
return;
}
else if (!strcmp(s, "cos"))
{
push(cos(pop()));
return;
}
else if (!strcmp(s, "tan"))
{
push(tan(pop()));
return;
}
else if (!strcmp(s, "exp"))
{
push(exp(pop()));
return;
}
else if (!strcmp(s, "pow"))
{
push(pow(pop(),pop()));
return;
}
else
{
printf("error: unknown command %s\n", s);
return;
}
}
getop函数增加处理字母的功能
#include <stdio.h>
#include <ctype.h>
#include "calc.h"
int getch(void);
void ungetch(int);
int getop(char s[])
{
int i, c;
while ((s[0] = c = getch()) == ' ' || c == '\t')
;
s[1] = '\0';
if (!isdigit(c) && !islower(c) && c != '.')
return c;
i = 0;
if (islower(c))
{
while (islower(s[++i] = c = getch()))
;
s[i] = '\0';
if (i == 1)
return VARIABLE;
else
return MATHOP;
}
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;
}
头文件calc.h
#define NUMBER '0'
#define MATHOP '1'
#define VARIABLE '2'
void push(double);
double pop(void);
int getop(char []);
int getch(void);
void ungetch(int);
其他函数没有放,可以看之前我的博客