本文主要是介绍HDU 1237 简单计算器(栈的中缀表达式求值),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Description
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
Input
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
Output
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
Sample Input
1 + 2
4 + 2 * 5 - 7 / 11
0
Sample Output
3.00
13.36
Solution
答题思路是将中缀表达式转换为后缀表达式求值,可以参考 > https://www.cnblogs.com/hantalk/p/8734511.html ,写的非常不错,这里采用变转换为后缀表达式变求值。表达式求值板题。
更新一波板。
#include <iostream>
#include <cstdio>
#include <string>
#include <stack>
#include <queue>
#include <map>
using namespace std;
struct node
{double num;char op;bool flag;
};
string str;
stack<node> s; //操作符栈
queue<node> q; //后缀表达式
map<char, int> op;
// 转为后缀表达式
void Change()
{double num;node temp;for (int i = 0; i < str.length();){if (str[i] >= '0' && str[i] <= '9'){// 如果是数字则标记为数字temp.flag = true;// 记录数字第一位temp.num = str[i++] - '0';while (i < str.length() && str[i] >= '0' && str[i] <= '9'){// 更新操作数temp.num = temp.num * 10 + (str[i] - '0');i++;}q.push(temp);// 压入后缀表达式队列}else{// 如果是操作符temp.flag = false;// 只要操作符栈顶的元素比该操作符优先级高// 就把操作符栈顶元素弹出到后缀表达式队列中while (!s.empty() && op[str[i]] <= op[s.top().op]){q.push(s.top());s.pop();}temp.op = str
这篇关于HDU 1237 简单计算器(栈的中缀表达式求值)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!