[ create a new paste ] login | about

Link: http://codepad.org/aNs8p7a1    [ raw code | output | fork ]

C, pasted on Jul 18:
#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>

int nextc;
#define peek(c)  (nextc == c)
#define match(c) (peek(c) ? (nextc = getchar()) : 0)

jmp_buf env;
void error(void)
{
  printf("syntax error.\n");
  while (!peek('\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("%.0f\n", exp0());
  return 0;
}

double exp0(void)
{                                   /* E -> TA */
  double v = term0();
  return exp1(v); 
}

double exp1(double v)
{
  if(match('+')) {                  /* A -> +TA */
    v += term0(); return exp1(v);
  } else if(match('-')) {           /* A -> -TA */
    v -= term0(); 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(); return term1(v);
  } else if(match('/')) {           /* B -> /FB */
    v /= factor(); 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';
      return atof(buf);
    }
  }
  if(match('(')) {             /* F -> (E) */
    double v = exp0();
    if(match(')')) return v;
    else error();
  } else {
    error();
  }
}
/* end */


Output:
1
Timeout


Create a new paste based on this one


Comments: