2 views
Skip to first unread message

varun agarwal

unread,
Mar 31, 2016, 2:35:09 PM3/31/16
to gpr...@googlegroups.com, Harshit Khanna
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <setjmp.h>
#include <math.h>

char *pb, *p;
jmp_buf env;

double eval() {
  double x;  char *q1, *q2;
  if (isspace(*--p)) {
    while (p>pb && isspace(*p)) --p;
    if (p>pb) switch (*p) {
        case '+': return eval()+eval();
        case '*': return eval()*eval();
        case '-': return x=eval(),eval()-x;
        case '/': return x=eval(),eval()/x;
case 'sin' : return sin(eval());
case 'cos' : return cos(eval());
case 'tan' : return tan(eval());
case 'sqrt' : return sqrt(eval());
case 'pow' : return x=eval(),pow(eval(),x);
//case 'dup' : x=eval(); return x,x;
//case 'swap' : x=eval(), y=eval()); return y,x
case 'print' : return eval();
case 'quit' : return 0;
default:  q1 = p+1;
                  while (!isspace(*--p)) ;
 if (x=strtod(++p,&q2),q2==q1) return x;
    }
  }
  longjmp(env,0);
}

int main() {
  int sz,c,n;
  double x;
  pb = malloc(sz=4);
  *pb = ' ';
  p = pb+1;
  while ((c=getchar())!=EOF)
    if (c!='\n') {
      n = p-pb;
      if (n+2==sz) pb = realloc(pb,sz*=2);
      p = pb+n;
      *p++ = c;
    } else {
      while (--p>pb && isspace(*p)) ;
      if (p++>pb) {
        *p++ = ' ';
        if (!setjmp(env)) {
          x = eval();
          while (--p>pb && isspace(*p)) ;
          if (p>pb)  longjmp(env,0);
          printf("%f\n",x);
        }
        else  printf("error\n");
        p = pb+1;
      }
    }
}


Just check this , also will have to modify a little for dup,swap,pop


--
Varun Agarwal

Shrey Shankar

unread,
Mar 31, 2016, 3:30:22 PM3/31/16
to gpr...@googlegroups.com, Harshit Khanna

I dont know the exact syntax of C, but swapping of top two elements, the algorithm goes like this

Stack stack = new Stack():
int first = stack.pop():
int second = stack.pop();

stack.push(second);
stack.push(first);

Anyway, you can find the part of your program on this link
http://www.learntosolveit.com/cprogramming/Ex_4.4_rpn_top_two_elements.html

--
--
You received this message because you are the chosen one.
The administrators of "GP rocks" have selected YOU...
So feel highly priviledged.....!!!
 
To post to this group, send email to gpr...@googlegroups.com
To unsubscribe from this group, send email to gprocks-u...@googlegroups.com
For more options, visit this group at http://groups.google.com/group/gprocks?hl=en
---
You received this message because you are subscribed to the Google Groups "GP rocks" group.
To unsubscribe from this group and stop receiving emails from it, send an email to gprocks+u...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

manoj kumar

unread,
Apr 5, 2016, 1:39:00 AM4/5/16
to gpr...@googlegroups.com, Harshit Khanna

Hahaha ..

Reply all
Reply to author
Forward
0 new messages