herry • 8天前
using namespace std; stackopt; int num[150], l = 1, r = 0;
int get_rank(char c) {
if (c == '(')
return 0;
else if (c == '+' || c == '-')
return 1;
else if (c == '*' || c == '-')
return 2;
return 3;
}
int main() {
string str, res = "";
cin >> str;
for (int i = 0; i < str.length(); i++) {
if (str[i] >= '0' && str[i] <= '9')
res = res + str[i] + ' ';
else if (str[i] == '(' || str[i] == '^') {
opt.push('(');
} else if (str[i] == ')') {
while (!opt.empty() && opt.top() != '(') {
res = res + opt.top();
res = res + ' ';
opt.pop();
}
opt.pop();
} else if (str[i] == '^')
opt.push(str[i]);
else {
while (opt.size() && get_rank(str[i]) <= get_rank(opt.top())) {
res = res + opt.top() + ' ';
opt.pop();
}
opt.push(str[i]);
}
}
while (opt.size() != 0) {
res = res + opt.top() + ' ';
opt.pop();
}
cout << res << endl;
for (int i = 0; i < res.length(); i++) {
if (str[i] >= '0' && str[i] <= '9') {
r++;
num[r] = str[i] - '0';
} else if (res[i] == ' ') {
continue;
} else {
int y = num[r];
r--;
int x = num[r];
r--;
r++;
if (res[i] == '+') {
num[r] = x + y;
} else if (res[i] == '-')
num[r] = x - y;
else if (res[i] == '*')
num[r] = x * y;
else if (res[i] == '/')
num[r] = x / y;
else
num[r] = pow(x, y);
for (int j = 1; j <= r; j++) {
if (j != r)
cout << ' ';
cout << num[j];
}
for (int j = i + 1; j <= res.length(); j++) {
cout << res[j];
}
cout << endl;
}
}
return 0 ;
}
评论:
请先登录,才能进行评论