计算器(栈),求大神指点
在代码中,应该创建两个栈,请问是创建一个char和一个int还是创建两个char型的
一个数据栈,建议用double吧
一个运算符栈
#include <stack> #include <string> #include <cstdlib> #include <iostream> class Calculate { private: double ans; std::string str; std::stack<char> operStack; std::stack<double> dataStack; public: void clear(); double calculate(); char precede(const char a, const char b); double oper(const double a, const char ch, const double b); friend std::istream& operator>>(std::istream &is, Calculate &cal); friend std::ostream& operator<<(std::ostream &os, const Calculate &cal); }; void Calculate::clear() { ans = 0.0L; while (!operStack.empty()) operStack.pop(); while (!dataStack.empty()) dataStack.pop(); operStack.push('#'); } double Calculate::calculate() { this->clear(); std::string data, ss(str + '#'); for (size_t i = 0;i != ss.size();i++) { switch (ss[i]) { case '+': case '-': case '*': case '/': case '(': case ')': case '#': if (data.size() != 0) { dataStack.push(atof(data.c_str())); data.clear(); } switch (precede(operStack.top(), ss[i])) { case '<': operStack.push(ss[i]); break; case '=': operStack.pop(); if (operStack.empty()) { return ans = dataStack.top(); } break; case '>': double a = dataStack.top(); dataStack.pop(); double b = dataStack.top(); dataStack.pop(); dataStack.push(oper(b, operStack.top(), a)); operStack.pop(); i--; // 回退 break; } break; case '.': case '0' ... '9': data += ss[i]; break; } } return ans = 0.0L; } char Calculate::precede(const char a, const char b) { std::string str = "+-*/()#"; char pre[][7] = { { '>', '>', '<', '<', '<', '>', '>' }, { '>', '>', '<', '<', '<', '>', '>' }, { '>', '>', '>', '>', '<', '>', '>' }, { '>', '>', '>', '>', '<', '>', '>' }, { '<', '<', '<', '<', '<', '=', '0' }, { '>', '>', '>', '>', '0', '>', '>' }, { '<', '<', '<', '<', '<', '0', '=' } }; return pre[str.find(a)][str.find(b)]; } double Calculate::oper(const double a, const char ch, const double b) { double sa(0.0L); switch (ch) { case '+': sa = a + b; break; case '-': sa = a - b; break; case '*': sa = a * b; break; case '/': sa = a / b; break; } return sa; } std::istream& operator>>(std::istream &is, Calculate &cal) { getline(is, cal.str); return is; } std::ostream& operator<<(std::ostream &os, const Calculate &cal) { os << cal.str << " = " << cal.ans; return os; } int main() { Calculate cal; std::cin >> cal; cal.calculate(); std::cout << cal.calculate(); return 0; }
[此贴子已经被作者于2016-3-18 13:21编辑过]