Advertisement
Guest User

rpn

a guest
Jan 22nd, 2017
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.73 KB | None | 0 0
  1. #define STACK_DEPTH 100
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #include<string.h>
  5. #include<ctype.h>
  6. #include<math.h>
  7. double stack[STACK_DEPTH];
  8. int sp=STACK_DEPTH;
  9. double pop(void)
  10. {
  11.     if(sp<STACK_DEPTH){
  12.        return stack[sp++];
  13.     }else{
  14.        return 0.0;
  15.     }
  16. }
  17. void push(double f)
  18. {
  19.      if(sp>0)
  20.         stack[--sp]=f;
  21.       }
  22. int getword(char* dst, const char* str, int limit)
  23.  {
  24.     int i, j, len = strlen(str);
  25.     for(i=0; i<len && isspace(str[i]); i++);
  26.     for(j=0; j<limit && (j+i)<len && !isspace(str[i+j]); j++)
  27.     dst[j]=str[i+j];
  28.     dst[j]='\0';
  29.     return i+j;
  30. }
  31. int main(void)
  32. {
  33.     printf("Podaj wyrażenie w rpn:\n");
  34.     double op2;
  35.     char line[100], tmp[100];
  36.     int i, c;
  37.     while(1){
  38.         i = 0;
  39.         fgets(line, 100, stdin);
  40.         while((c=getword(tmp, &line[i], 100)) && strlen(tmp)){
  41.             if(strcmp(tmp, "sin")==0)
  42.                 push(sin(pop()));
  43.             else if(strcmp(tmp, "cos")==0)
  44.                 push(cos(pop()));
  45.             else if(strcmp(tmp, "pow")==0){
  46.                 op2 = pop();
  47.                 push(pow(pop(),op2));
  48.             }
  49.             else if(strcmp(tmp, "+")==0)
  50.                 push(pop()+pop());
  51.             else if(strcmp(tmp, "-")==0){
  52.                 op2 = pop();
  53.                         push(pop()-op2);}
  54.             else if(strcmp(tmp, "*")==0)
  55.                 push(pop()*pop());
  56.             else if(strcmp(tmp, "/")==0){
  57.                 op2 = pop();
  58.  
  59.                             push(pop()/op2);}
  60.             else if(strcmp(tmp, "=")==0)
  61.                 printf("%f\n", pop());
  62.             else
  63.             push(atof(tmp));
  64.             i+=c;
  65.         }
  66.         if (line[0] == '\n') break;
  67.     }
  68.     return 0;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement