编写程序 expr,它从命令行计算逆波兰表达式,其中每个运算符或操作数是一个单独的参数。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#define MaxOp 100
#define number '0'
#define MaxRowNum 100
char getop(char *);
void push(double);
double pop(void);
double myatof(char *);
int main()
{
int argc;
char s[MaxOp],*argv[MaxRawNum];
double num, op;
char **temp = argv;
void ungets(char[]);
scanf("%d", &argc);
for (int i = 1; i < argc; i++) {
argv[i] = (char *)malloc(MaxRowNum * sizeof(char));
scanf("%s", argv[i]);
}
while (--argc > 0)
{
ungets(*++temp);
switch (getop(s))
{
case number:
push(atof(s));
break;
case '+':
num = pop() + pop();
push(num);
break;
case '-':
op = pop();
num = pop() - op;
push(num);
break;
case '*':
num = pop() * pop();
push(num);
break;
case '/':
op = pop();
if (op != 0.0) {
num = pop() / op;
push(num);
}
else
printf("error: zero divisor\n");
break;
default:
printf("error: unknown command %s\n",s);
argc = 1;
break;
}
}
printf("\t%.8g\n", pop());
return 0;
}
double myatof(char *s)
{
int sign;
double num, pow;
num = 0.0;
pow = 1.0;
sign = (*s == '-') ? -1 : 1;
while (isdigit(*s))
{
num = 10.0 * num + *s - '0';
}
if (*s == '.')
s++;
while (isdigit(*s))
{
num = 10.0 * num + *s - '0';
pow *= 10.0;
}
num = sign * num / pow;
return num;
}
#define MaxVal 100
double operand[MaxVal];
int place = 0;
void push(double op)
{
if (place < MaxVal)
operand[place++] = op;
else {
printf("the stack of operand is full, can't push");
return;
}
}
double pop(void)
{
if(place > 0)
return operand[--place];
else
{
printf("the stack is empty,can't pop\n");
return 0.0;
}
}
char getch(void);
void ungetch(char);
char getop(char *s)
{
char c;
while ((*s = c = getch()) == ' ' || c == '\t')
;
*(s+1) = '\0';
if (!isdigit(c) && c != '.')
return c;
if (isdigit(*++s = c = getch()))
;
if (c == '.')
while(isdigit(*++s = c = getch()))
;
if (c != EOF)
ungetch(c);
*s = '\0';
return number;
}
void ungets(char s[])
{
void ungetch(char);
int len = strlen(s);
while (len > 0)
ungetch(s[--len]);
}
#define MaxSize 100
char buf[MaxSize];
char *bufp = buf;
char getch()
{
return (bufp > buf) ? *--bufp : getchar();
}
void ungetch(char c)
{
if (bufp < buf + MaxSize)
{
*bufp = c;
bufp++;
}
else
printf("there is no space in buffer\n");
}
|