题解 | #计算表达式#写了两个钟,太垃圾了
计算表达式
https://www.nowcoder.com/practice/7b18aa6b7cc14f8eaae6b8acdebf890b
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stack>
#include <map>
using namespace std;
map<char, int> mymap = {
{'+', 0}, {'-', 0}, {'/', 1}, {'*', 1}
};
float jisusan(float x, float y, char oper) {
float res;
switch (oper) {
case '+':
res = x + y;
break;
case '-':
res = x - y;
break;
case '*':
res = x * y;
break;
case '/':
res = x / y;
break;
}
return res;
}
int main() {
stack<float> numStack;
stack<char> operStack; //operator 运算符
string expr; //expression 表达式
while (getline(cin, expr)) {
for (int i = 0; i < expr.size(); i++) {
if (expr[i] >= '0' && expr[i] <= '9') {
//表明这是一个数字 可能有很多位
int j = i;
while (j < expr.size() && expr[j] >= '0' && expr[j] <= '9') {
j++;
continue;
}
//此时j越界,或者j是操作符 i 到 j - 1为数字
float num = 0;
while (i != j) {
num *= 10;
num += (expr[i] - '0');
i++;
}
i--;
numStack.push(num);
} else {
if (!operStack.empty()) {
while (!operStack.empty() && mymap[operStack.top()] >= mymap[expr[i]]) {
//栈顶的优先级 >= 当前的优先级
//弹出两个数和操作符计算结果然后放到numstack
float a1 = numStack.top();
numStack.pop();
float a2 = numStack.top();
numStack.pop();
char c = operStack.top();
operStack.pop();
float res = jisusan(a2, a1, c);
numStack.push(res);
}
operStack.push(expr[i]);
} else {
operStack.push(expr[i]);
}
}
}
while (!operStack.empty()) {
float a1 = numStack.top();
numStack.pop();
float a2 = numStack.top();
numStack.pop();
char c = operStack.top();
operStack.pop();
float res = jisusan(a2, a1, c);
numStack.push(res);
}
float a1 = numStack.top();
numStack.pop();
//printf("%f\n", a1); //这里用cout方便点
cout << a1 << endl;
}
}
// 64 位输出请用 printf("%lld")

