#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>
int nextc;
int match(int c)
{
if (nextc == c) {
do {
nextc = getchar();
} while (nextc == ' ');
return 1;
} else {
return 0;
}
}
jmp_buf env;
void error(viod)
{
printf("syntax error.\n");
while (nextc != '\n') {
nextc = getchar();
}
longjmp(env, 1);
}
double exp0(void);
double exp1(double);
double term0(void);
double term1(double);
double factor(void);
int main()
{
setjmp(env);
nextc = getchar();
printf("\nAnswer = %lf\n", exp0());
}
double exp0(void)
{ /* E -> TA */
double v = term0();
return exp1(v);
}
double exp1(double v)
{
if(match('+')) { /* A -> +TA */
v += term0(); printf("+ "); return exp1(v);
} else if(match('-')) { /* A -> -TA */
v -= term0(); printf("- "); return exp1(v);
} else
return v; /* A -> epsilon */
}
double term0(void) { /* T -> FB */
double v = factor();
return term1(v);
}
double term1(double v) {
if(match('*')) { /* B -> *FB */
v *= factor(); printf("* "); return term1(v);
} else if(match('/')) { /* B -> /FB */
v /= factor(); printf("/ "); return term1(v);
} else /* B -> epsilon */
return v;
}
#define N 1024
double factor(void) { /* F -> 0...9 */
static char buf[N];
static char numtab[] = "0123456789.", *p;
int flag, i;
i = 0;
while (1) {
flag = 0;
for (p = numtab; *p != '\0'; p++) {
if (match(*p)) {
flag = 1;
break;
}
}
if (flag == 1) {
buf[i++] = (char)*p;
continue;
} else {
if (i == 0)
break;
else
buf[i] = '\0';
printf("%s ", buf);
return atof(buf);
}
}
if(match('(')) { /* F -> (E) */
double v = exp0();
if(match(')')) return v;
else error();
} else {
error();
}
}
/* end */