|
| 1 | +#include <iostream> |
| 2 | +#include "Stack.cpp" |
| 3 | +#include "NotSTL.cpp" |
| 4 | + |
| 5 | +double pow(double number, int times){ |
| 6 | + double result = number; |
| 7 | + for(int i=1; i<times; i++) |
| 8 | + result *= number; |
| 9 | + return result; |
| 10 | +} |
| 11 | + |
| 12 | +double getElement(LStack<double>& st){ |
| 13 | + if(st.isEmpty()){ |
| 14 | + std::cerr<<"Invalid input format!\n"; |
| 15 | + return 0; |
| 16 | + } |
| 17 | + return st.pop(); |
| 18 | +} |
| 19 | + |
| 20 | +double calculate(char* expression){ |
| 21 | + LStack<double> st; |
| 22 | + double sum = 0; |
| 23 | + |
| 24 | + int n = getLength(expression); |
| 25 | + |
| 26 | + for(int i=0; i<n; i++){ |
| 27 | + if(expression[i] >= '0' && expression[i] <= '9'){ |
| 28 | + double toPush = expression[i] - '0'; |
| 29 | + while(expression[i+1] >= '0' && expression[i+1]<= '9') |
| 30 | + { |
| 31 | + toPush*=10; |
| 32 | + toPush += expression[i+1] - '0'; |
| 33 | + i++; |
| 34 | + } |
| 35 | + if(expression[i+1] == '.'){ |
| 36 | + i++; |
| 37 | + int placeAfterDecimal=1; |
| 38 | + while(expression[i+1] >='0' && expression[i+1] <= '9'){ |
| 39 | + toPush += (expression[i+1] - '0') * pow(0.1, placeAfterDecimal); |
| 40 | + i++; |
| 41 | + } |
| 42 | + } |
| 43 | + st.push(toPush); |
| 44 | + } else { |
| 45 | + if(expression[i]!=' '){ |
| 46 | + |
| 47 | + double second = getElement(st); |
| 48 | + double first = getElement(st); |
| 49 | + if(expression[i] == '+') |
| 50 | + st.push(first + second); |
| 51 | + else if(expression[i] == '-') |
| 52 | + st.push(first - second); |
| 53 | + else if(expression[i] == '*') |
| 54 | + st.push(first * second); |
| 55 | + else if(expression[i] == '/') |
| 56 | + st.push(first/second); |
| 57 | + else if(expression[i] == '%'){ |
| 58 | + if(second!=(int)second || first!=(int)first){ |
| 59 | + std::cerr<<"Trying to use % operation on double arguments!\n"; |
| 60 | + return 0; |
| 61 | + } |
| 62 | + st.push((int)first%(int)second); |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + double result = st.pop(); |
| 68 | + if(!st.isEmpty()){ |
| 69 | + std::cerr<<"Invalid input format!\n"; |
| 70 | + return 0; |
| 71 | + } |
| 72 | + return result; |
| 73 | +} |
| 74 | + |
| 75 | +int main(){ |
| 76 | + char *expression = new char[100]; |
| 77 | + std::cin.getline(expression, 100); |
| 78 | + |
| 79 | + std::cout<<calculate(expression)<<std::endl; |
| 80 | + |
| 81 | + return 0; |
| 82 | +} |
0 commit comments