低级计算器。。。

对于无乘号的括号,即类似2(7+2)这种尚不完善。。

#include <iostream> #include <stack> #include <string> #include <cmath> using namespace std; stack<double> _operand; stack<char> _operator; int isp(char c) { switch(c) { case '+': case '-': return 2; case '*': case '/': return 4; case '^': return 6; case '(': return 0; } } int osp(char c) { switch(c) { case '+': case '-': return 1; case '*': case '/': return 3; case '^': return 5; case '(': return 8; case ')': return -1; } } void cal() { char c = _operator.top(); _operator.pop(); if(c == '(') return; double x = _operand.top(); _operand.pop(); double y = _operand.top(); _operand.pop(); switch(c) { case '+': _operand.push(y + x); break; case '-': _operand.push(y - x); break; case '*': _operand.push(y * x); break; case '/': _operand.push(y / x); break; case '^': _operand.push(pow(y, x)); break; } } int main() { while(!_operator.empty()) { _operator.pop(); } while(!_operand.empty()) { _operand.pop(); } string s; cin >> s; string num = ""; for(int i = 0; i < s.size(); i++) { if((s[i] >= '0'&& s[i] <= '9') || s[i] == '.') { num += s[i]; }else { if(!num.empty()) { _operand.push(atof(num.c_str())); num.clear(); } while(!_operator.empty() && isp(_operator.top()) > osp(s[i])) { cal(); } if(s[i] != ')') _operator.push(s[i]); } } if(!num.empty()) { _operand.push(atof(num.c_str())); num.clear(); } while(!_operator.empty()) { cal(); } cout << _operand.top() << endl; return 0; } 

你可能感兴趣的:(c,String)