实现简单计算器
思路:输入的为中缀表达式,计算机不利于计算
- 将中缀表达式转换为后缀表达式
- 对后缀表达式用栈模拟计算过程
#pragma warning(diable:4996)
#include<iostream>
#include<stack>
#include<queue>
#include<string>
#include<map>
using namespace std;
//定义字符结构
struct node
{
double num;
char op;
bool flag;
};
//运算符栈
stack<node> oper;
//存储后缀表达式的队列
queue<node> q;
//记录运算符优先级的关系
map<char, int> op;
//中缀表达式变为后缀表达式
void change(string &str)
{
node temp;
for (int i = 0; i < str.length();)
{
if (str[i] >= '0' && str[i] <= '9')
{
temp.num = 0;
temp.flag = true;
while (i < str.length()&&str[i] >= '0' && str[i] <= '9')
{
temp.num = temp.num * 10 + int(str[i]-'0');
i++;
}
q.push(temp);
}
else
{
temp.flag = false;
temp.op = str[i];
while(!oper.empty() && (op[str[i]] <= op[oper.top().op]))
{
q.push(oper.top());
oper.pop();
}
oper.push(temp);
i++;
}
}
while (!oper.empty())
{
q.push(oper.top());
oper.pop();
}
}
//计算后缀表达式
double cal()
{
while (!q.empty())
{
if (q.front().flag == true)
{
oper.push(q.front());
q.pop();
}
else
{
char op = q.front().op;
q.pop();
double num1 = oper.top().num;
oper.pop();
double num2 = oper.top().num;
oper.pop();
node result;
result.flag = true;
if (op == '+') result.num = num1 + num2;
else if (op == '-') result.num = num2 - num1;
else if (op == '*') result.num = num1 * num2;
else if (op == '/') result.num = num2 / num1;
oper.push(result);
}
}
return oper.top().num;
}
int main()
{
op['+'] = op['-'] = 0;
op['*'] = op['/'] = 1;
while (!oper.empty())
{
oper.pop();
}
string str;
getline(cin, str);
cout << "中缀表达式:" << str << endl;
change(str);
//cout << "后缀表达式:" << endl;
/*while (!q.empty())
{
if (q.front().flag == true) cout << q.front().num;
else cout << q.front().op;
q.pop();
}*/
cout << endl;
cout << "运算结果:" << cal() << endl;
system("pause");
return 0;
}