Share a big cow's artificial intelligence tutorial. Zero-based! Easy to understand! Funny and humorous! Hope you join the artificial intelligence team too! Please click http://www.captainbed.net
/*
* A reverse Polish calculator
*
* ReversePolishCalculator.c - by FreeMan
*/
#include <stdio.h>
#include <stdlib.h> /* For atof() */
#define MAXOP 100 /* Max size of operand or operator */
#define NUMBER '0' /* Signal that a number was found */
int GetOp(char[]);
void Push(double);
double Pop(void);
/* Reverse Polish calculator */
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("\t%.8g\n", Pop());
break;
default:
printf("error: unknown command %s\n", s);
break;
}
}
return 0;
}
#define MAXVAL 100 /* Maximum depth of val stack */
int sp = 0; /* Next free stack position */
double val[MAXVAL]; /* Value stack */
/* Push: Push f onto value stack */
void Push(double f)
{
if (sp < MAXVAL)
{
val[sp++] = f;
}
else
{
printf("error: stack full, can’t push %g\n", f);
}
}
/* Pop: Pop and return top value from stack */
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: Get next character or numeric operand */
int GetOp(char s[])
{
int i, c;
while ((s[0] = c = GetCh()) == ' ' || c == '\t')
;
s[1] = '\0';
if (!isdigit(c) && c != '.') /* Not a number */
{
return c;
}
i = 0;
if (isdigit(c)) /* Collect integer part */
{
while (isdigit(s[++i] = c = GetCh()))
;
}
if (c == '.') /* Collect fraction part */
{
while (isdigit(s[++i] = c = GetCh()))
;
}
s[i] = '\0';
if (c != EOF)
{
UngetCh(c);
}
return NUMBER;
}
#define BUFSIZE 100
char buf[BUFSIZE]; /* Buffer for UngetCh */
int bufp = 0; /* Next free position in buf */
int GetCh(void) /* Get a (possibly pushed-back) character */
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
void UngetCh(int c) /* Push character back on input */
{
if (bufp >= BUFSIZE)
{
printf("UngetCh: too many characters\n");
}
else
{
buf[bufp++] = c;
}
}
// Output:
/*
1 2 + 3 4 - * 5 6 + /
-0.27272727
*/