C++简易计算器:包括加减乘除和括号
输入:任意包括'+','-','*','/','(',')'空格以及数字(可以是浮点数)的合法运算表达式
输出:运算结果(浮点数)
代码实现:
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
double calculate(string s){
// initialize
vector<string> init;
int len = s.length();
string mem = "";
bool minus_check = false;
for(int i=0; i<len; ++i){
switch(s[i]){
case '(': case ')': case '+': case '-': case '*': case '/':
if(mem.length()){
init.push_back(mem);
mem = "";
minus_check = true;
}
if(s[i] == '-' && minus_check == false){
init.push_back("0");
}
mem += s[i];
init.push_back(mem);
mem = "";
if (s[i] == '(')
minus_check = false;
break;
case ' ':
if(mem.length()){
init.push_back(mem);
mem = "";
minus_check = true;
}
break;
default:
mem += s[i];
break;
}
}
if(mem.length()){
init.push_back(mem);
mem = "";
}
// process
stack<string> st1;
deque<string> st2;
int siz = init.size();
for(int i=siz-1; i>=0; --i){
if(init[i] != "("){
st1.push(init[i]);
}
if(init[i] == "(" || i == 0){
while(!st1.empty() && st1.top() != ")"){
string opn = st1.top();
st1.pop();
if(opn == "*" || opn == "/"){
double rn = stod(st1.top());
st1.pop();
double ln = stod(st2.back());
st2.pop_back();
if(opn == "*") ln *= rn;
else ln /= rn;
st2.push_back(to_string(ln));
}
else{
st2.push_back(opn);
}
}
if(!st1.empty()) st1.pop();
double ans = 0;
while(!st2.empty()){
string opn = st2.front();
st2.pop_front();
if(opn == "+" || opn == "-"){
double rn = stod(st2.front());
st2.pop_front();
if(opn == "+") ans += rn;
else ans -= rn;
}
else{
ans = stod(opn);
}
}
st1.push(to_string(ans));
}
}
double ans = 0;
while(!st1.empty()){
string opn = st1.top();
st1.pop();
if(opn == "+" || opn == "-"){
double rn = stod(st1.top());
st1.pop();
if(opn == "+") ans += rn;
else ans -= rn;
}
else{
ans = stod(opn);
}
}
return ans;
}
};
int main(){
string cals;
cin>>cals;
Solution sol;
double ans = sol.calculate(cals);
cout<<ans<<endl;
}

浙公网安备 33010602011771号