当前位置: 代码迷 >> 综合 >> C程序设计语言 4-6
  详细解决方案

C程序设计语言 4-6

热度:80   发布时间:2024-01-20 04:23:13.0

练习4-6 给计算机程序增加处理变量的命令(提供26个具有单个英文字母变量名的变量很容易)。增加一个变量存放最近打印的值。

主函数:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "calc.h"#define MAXLEN 100
#define MAXOP 100int 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);elseprintf("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;}elsepush((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;elsereturn 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);

其他函数没有放,可以看之前我的博客