思路:扫描完整个输入字符串之后,挨个输出字符,如果一直输出的是数字,就重新存到另一个字符串,直到检测到出现操作符为止,此时将字符串中的数字字符串利用stod转换为整数压入数据栈。
操作符方面,首先维护一个map,存储各级运算符之间的优先级关系,当输出的是操作符的时候,与操作符栈顶元素进行优先级比较,如果该操作符的优先级小于栈顶操作符的优先级,则从数据栈中弹出两个元素与该操作符进行操作,得到的结果再压入数据栈。否则直接将操作符入栈,继续下一个循环
循环终止在检测到\0符号的时候,break
/*对于一个不存在括号的表达式进行计算
输入描述:
存在多组数据,每组数据一行,表达式不存在空格
输出描述:输出结果
示例1
输入:
6/2+3+3*4
输出:18 */
#include <cstdio>
#include <iostream>
#include <stack>
#include <string>
#include <map>
using namespace std;
int main() {
char str[1000] = {0};
stack<char> opstk;
stack<double> numstk;
map<char, int> priority = {
{'\0', 0}, {'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}
};
while (scanf("%s", str) != EOF) {
string numstr = "";
for (int i = 0;; ++i) {
if (str[i] >= '0' && str[i] <= '9') {
numstr.push_back(str[i]);
} else {
double num = stod(numstr);
numstr = "";
numstk.push(num);
while (!opstk.empty() && priority[str[i]] <= priority[opstk.top()]) {
double rhs = numstk.top();
numstk.pop();
double lhs = numstk.top();
numstk.pop();
char curop = opstk.top();
opstk.pop();
if (curop == '+') numstk.push(lhs + rhs);
else if (curop == '-') {
numstk.push(lhs - rhs);
} else if (curop == '*') {
numstk.push(lhs * rhs);
} else if (curop == '/') {
numstk.push(lhs / rhs);
}
}
if (str[i] == '\0') {
printf("%d\n", (int)numstk.top());
break;
} else {
opstk.push(str[i]);
}
}
}
}
return 0;
}



京公网安备 11010502036488号