全文代码逐行注释;
基本思路同牛客KY129, 采用王道复试2023章节4.4思路
如有错误,请多指教 :)
//
// Created by Perceive109 on 2023/1/20.
//
# include "iostream"
# include "string"
# include "stack"
# include "map"
using namespace std;
// 计算:左操作数、右侧操作数、操作符
double calculate(double leftOperand, double rightOperand, char Operator) {
if (Operator == '+') return leftOperand + rightOperand;
else if (Operator == '-')return leftOperand - rightOperand;
else if (Operator == '*') return leftOperand * rightOperand;
else if (Operator == '/') return leftOperand / rightOperand;
return -1;
}
// 基本思路同牛客KY129,采用王道复试2023章节4.4思路
int main() {
// I/O加速
std::ios::sync_with_stdio(false);
std::cin.tie(0);
map<char, int> priority = { // 优先级判定(运算符,优先级)
{'$', 0},
{'+', 1},
{'-', 1},
{'*', 2},
{'/', 2}};
string str; // 变量定义:输入的字符串
while (getline(cin, str)) { // 使用getline()获取一行
str.push_back('$'); // 附加结尾符号'$',由于优先级最低,确保所有数值都进行运算
stack<double> Operand; // 变量定义:操作数栈
stack<char> Operator; // 变量定义:操作符栈
string num; // 处理如11这样一个以上的数值
// 开始处理输入的数据
for (int i = 0; i < str.size(); ++i) {
if (str[i] >= '0' && str[i] <= '9') { // 如果:当前输入是数字字符
num += str[i]; // 保存到num中
if (str[i] != str.size() - 1 && !(str[i + 1] >= '0' && str[i + 1] <= '9')) { // 如果下一个数不是数字
Operand.push(stod(num)); // 将数值入栈;注释:stod(String TO Double) 将字符串转换为double
num.clear(); // 清空num
}
} else { // 不是数字就是字符(+ - * / $)
while (!Operator.empty() && priority[Operator.top()] >= priority[str[i]]) { // 新来的(当前)运算符优先级更低
double rightOperand = Operand.top();// 首先弹出的是右操作数
Operand.pop();
double leftOperand = Operand.top(); // 其次弹出的是左操作数
Operand.pop();
Operand.push(calculate(leftOperand, rightOperand, Operator.top())); // 将新的结算结果压栈
Operator.pop();
}
Operator.push(str[i]); // 此时比当前元素符优先级高的都完成了运算,将当前运算符压入栈中
}
}
// 运算完成,此时操作数栈顶元素即为结果,将其输出:
cout << Operand.top() << endl;
}
return 0;
}

京公网安备 11010502036488号