题解 | 计算表达式
计算表达式
https://www.nowcoder.com/practice/7b18aa6b7cc14f8eaae6b8acdebf890b
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <vector>
#include <stack>
using namespace std;
int main() {
string str;
stack<float> ns;
stack<char> os;
getline(cin >> ws, str);
vector<char>cs(str.begin(), str.end());
for (int i = 0; i < cs.size(); ) {
char c = cs[i];
if (c <= '9' && c >= '0') {
// 当前字符是数字,循环吃掉所有数字
int j = i + 1;
float num = c - '0';
while (j < cs.size() && cs[j] <= '9' && cs[j] >= '0') {
num = num * 10 + cs[j] - '0';
j++;
}
ns.push(num);
i = j;
}
else {
os.push(c);
i++;
continue;
}
if (ns.size() >= 2) {
char o = os.top();
if (o == '*') {
float r = ns.top();
ns.pop();
float l = ns.top();
ns.pop();
float ans = r * l;
ns.push(ans);
os.pop();
}
if (o == '/') {
float r = ns.top();
ns.pop();
float l = ns.top();
ns.pop();
float ans = l / r;
ns.push(ans);
os.pop();
}
}
}
float sum = 0;
while (!os.empty()) {
char o = os.top();
float top = ns.top();
if (o == '+')
{
sum += top;
}
else {
sum -= top;
}
ns.pop();
os.pop();
}
cout << sum + ns.top() << endl;
ns.pop();
}

