#include<iostream>
#include<sstream>
#include<string>
#include<stack>
#include<cstdlib>
#pragma warning(disable:4996)
using namespace std;
#define ll long long
#define maxlen 100
int calculate(string s) {
istringstream in('+' + s + '+');
long long total = 0, term = 0, n;
char op;
while (in >> op) {
if (op == '+' || op == '-') {
total += term;
in >> term;
term *= 44 - op;
}
else {
in >> n;
if (op == '*')
term *= n;
else
term /= n;
}
}
return total;
}
int main(){
string s;
while (cin >> s){
stack<string> sst;
string tmp;
sst.push("");
for (int i = 0; i < s.size(); i++){
if (s[i] == '('){
sst.push("");
}
else if (s[i] == ')'){
char ret[maxlen];
itoa(calculate(sst.top()),ret,10);
sst.pop();
sst.top() += ret;
}
else sst.top() += s[i];
}
cout << calculate(sst.top()) << endl;
}
}
含括号和四则运算符的简单表达式的计算【c++ 50 lines】
最新推荐文章于 2022-04-29 17:50:30 发布