Guest User

Untitled

a guest
Nov 14th, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. Polish.h
  2. class polish{
  3. double eval;
  4. char* infix;
  5. char* postfix;
  6. int priority(char ch);
  7. int isOperator(char ch);
  8. int operate(int a, int b, char op);
  9. int caracter(char c);
  10. public:
  11. polish(char *ch);
  12. void ReversePolishNotation();
  13. void ReversePolishEvaluate();
  14. };
  15.  
  16.  
  17. Polish.cpp
  18. #include<stdio.h>
  19. #include<string.h>
  20. #include<iostream.h>
  21.  
  22. polish::polish(char *ch)
  23. {
  24. strcat(infix,ch);
  25. }
  26.  
  27. int polish::priority(char ch)
  28. { if (ch=='*') return 3;
  29. if (ch=='/') return 4;
  30. if (ch=='+') return 1;
  31. if (ch=='-‘) return 2;
  32. return 0;
  33. }
  34.  
  35.  
  36. int polish::isOperator(char c)
  37. { if(priority(c)>0) return 1;
  38. else return 0;
  39. }
  40.  
  41. int polish::caracter(char c)
  42. { int ret;
  43. if (c== '0') ret=0;
  44. if (c== '1') ret=1;
  45. if (c== '2') ret=2;
  46. if (c== '3') ret=3;
  47. if (c== '4') ret=4;
  48. if (c== '5') ret=5;
  49. if (c== '6') ret=6;
  50. if (c== '7') ret=7;
  51. if (c== '8') ret=8;
  52. if (c== '9') ret=9;
  53. return ret;
  54. }
  55.  
  56. void polish::ReversePolishNotation()
  57. { int i;
  58. char *ret;
  59. ret="";
  60. char c;
  61. char st[10];
  62. int top=-1;
  63. i=0;
  64. while(i<strlen(infix))
  65. { if(!isOperator(*(infix+i)))
  66. ret=ret+(*(infix+i));
  67. else{
  68. while((top>=0)&&(priority(st[top])>=priority(*(infix+i))))
  69. { c=st[top];
  70. top--;
  71. ret+=c;
  72. }
  73. top++;
  74. st[top]=*(infix+i);
  75. }
  76. i++;
  77. }
  78. while(top>=0)
  79. { c=st[top];
  80. top--;
  81. ret+=c;
  82. }
  83. postfix=ret;
  84. cout<<ret;
  85. }
  86.  
  87. int polish::operate(int a, int b, char op)
  88. { int rez;
  89. if (op=='+') rez=a+b;
  90. if (op=='-') rez=a-b;
  91. if (op=='*') rez=a*b;
  92. if (op=='/') rez=a/b;
  93. return rez;
  94. }
  95.  
  96. void polish::ReversePolishEvaluate()
  97. { int st[10];
  98. int a,b;
  99. int i,top=-1;
  100. i=0;
  101. while(i<strlen(postfix))
  102. { if(isOperator(*(postfix+i)))
  103. { b=st[top];
  104. top--;
  105. a=st[top];
  106. st[top]=operate(a,b,*(postfix+i));
  107. }
  108. else
  109. {
  110. top++;
  111. st[top]=caracter(*(postfix+i));
  112. }
  113. i++;
  114. }
  115. eval=st[top];
  116. cin>>eval;
  117. }
  118.  
  119.  
  120. exPolish.cpp
  121. void main(){
  122. char *sir;
  123. cout<<"Introduceti expresia de evaluat"<<endl;
  124. cin>>sir;
  125. polish p(sir);
  126. p.ReversePolishNotation();
  127. p.ReversePolishEvaluate();
  128. }
Add Comment
Please, Sign In to add comment