标签:style io os ar sp on 代码 c amp
闲来无事,写个四则运算的计算式【包括+,-,*,/,没有括号】;
代码如下:
#include <iostream> #include <stack> #include <string> using namespace std; class Calc { public: int judge (const string &str) { if (str.find ('=') == string::npos) { cout<<"input error"<<endl; return -1; } } int process (int a, int b, char op) { if (op == '+') { return a + b; } if (op == '-') { return a - b; } if (op == '*') { return a * b; } return a/b; } int result (const string &str) { string::const_iterator data = str.begin (); if (judge (str) == -1) return -1; while (*data != '=') { if (*data == '*') { numA = num.top (); num.pop (); data++; numB = *data - '0'; num.push (process (numA, numB, '*')); }else if (*data == '/') { numA = num.top (); num.pop (); data++; numB = *data - '0'; num.push (process (numA, numB, '/')); } else if (*data >= '0' && *data <= '9') { num.push (*data - '0'); }else { op.push (*data); } data++; } while (!op.empty ()) { numA = num.top (); num.pop (); numB = num.top (); num.pop (); num.push (process (numB, numA, op.top ())); op.pop (); } return num.top (); } private: stack <int> num; stack <char> op; int numA; int numB; };
int main () { string data; Calc calc; while (cin>>data) { cout<<calc.result (data)<<endl; } return 0; }
标签:style io os ar sp on 代码 c amp
原文地址:http://blog.csdn.net/u013316504/article/details/39457851