代码拉取完成,页面将自动刷新
#include <iostream>
#include <stack>
#include <string>
#include <sstream>
using namespace std;
// 判断是否为运算符
bool is_operator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
// 计算表达式的值
int calculate(int a, int b, char op) {
if (op == '+') {
return a + b;
}
else if (op == '-') {
return a - b;
}
else if (op == '*') {
return a * b;
}
else if (op == '/') {
return a / b;
}
return 0;
}
// 计算表达式的值和计算过程
pair<int, string> evaluate(string expr) {
stack<int> nums; // 存放数字的栈
stack<char> ops; // 存放运算符的栈
stringstream process; // 记录计算过程
for (int i = 0; i < expr.length(); i++) {
if (expr[i] == ' ') {
continue;
}
else if (expr[i] == '(') {
ops.push(expr[i]);
process << "(";
}
else if (isdigit(expr[i]) || expr[i] == '-') {
int num = 0;
bool negative = false;
if (expr[i] == '-') {
negative = true;
i++;
}
while (i < expr.length() && isdigit(expr[i])) {
num = num * 10 + (expr[i] - '0');
i++;
}
if (negative) {
num = -num;
}
nums.push(num);
i--;
process << num;
}
else if (expr[i] == ')') {
while (!ops.empty() && ops.top() != '(') {
int b = nums.top();
nums.pop();
int a = nums.top();
nums.pop();
char op = ops.top();
ops.pop();
int result = calculate(a, b, op);
nums.push(result);
process << " " << op << " " << b << ") = " << result;
}
if (!ops.empty()) {
ops.pop(); // 弹出左括号
}
}
else if (is_operator(expr[i])) {
while (!ops.empty() && ops.top() != '(' && ((expr[i] != '*' && expr[i] != '/') || (ops.top() == '*' || ops.top() == '/'))) {
int b = nums.top();
nums.pop();
int a = nums.top();
nums.pop();
char op = ops.top();
ops.pop();
int result = calculate(a, b, op);
nums.push(result);
process << " " << op << " " << b << ") = " << result;
}
ops.push(expr[i]);
process << " " << expr[i] << " ";
}
}
while (!ops.empty()) {
int b = nums.top();
nums.pop();
int a = nums.top();
nums.pop();
char op = ops.top();
ops.pop();
int result = calculate(a, b, op);
nums.push(result);
process << " " << op << " " << b << ") = " << result;
}
return make_pair(nums.top(), process.str());
}
int main() {
string expr;
getline(cin, expr);
auto result = evaluate(expr);
cout << result.first << endl;
cout << "计算过程:" << result.second << endl;
return 0;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。