利用栈实现简单的四则运算,有待提升的地方有,不支持负数的运算,只支持0-9之间数值的计算
代码如下
#include <iostream>
#include <stack>
#include <string>
using namespace std;
void InfixToPostfix(string &str1, string &str2, stack<char> &s)
{
char ch, temp;
for (size_t i = 0; i != str1.size(); ++i)
{
ch = str1[i]; //获取当前字符
if (ch >= '0' && ch <= '9')
str2.push_back(ch); //放入str2中
if (ch == '(')
s.push(ch); //入栈
if (ch == ')') //右括号
{
do{
temp = s.top(); //获取当前栈顶元素
if (temp != '(')
{
str2.push_back(temp);
s.pop(); //出栈
}
else
{
s.pop();
break;
}
} while (!s.empty());
}
if (ch == '*' || ch == '/') //处理乘号及除号
{
if (s.empty()) //栈中无符号
{
s.push(ch);
continue;
}
temp = s.top();
if (temp == '+' || temp == '-' || temp == '(')
s.push(ch); //入栈
if (temp == '*' || temp == '/')
{
str2.push_back(temp);
s.pop();
s.push(ch);
}
}
if (ch == '+' || ch == '-')
{
if (s.empty()) //栈中无符号
{
s.push(ch);
continue;
}
temp = s.top();
if (temp == '(')
s.push(ch);
if (temp == '+' || temp == '-')
{
str2.push_back(temp);
s.pop();
s.push(ch);
}
if (temp == '*' || temp == '/')
{
str2.push_back(temp);
s.pop();
if (s.empty())
s.push(ch); //第一种情况直接放
//特殊情况处理
else
{
temp = s.top(); //获取下一个符号
if (temp == '-' || temp == '+')
{
str2.push_back(temp);
s.pop();
}
s.push(ch);
}
}
}
}
//处理栈中剩余部分
while (!s.empty())
{
temp = s.top();
str2.push_back(temp);
s.pop();
}
}
//后缀表达式求值
int GetResult(string &str2)
{
stack<int> is;
int t1, t2, t3;
char ch;
//扫描整个后缀表达式
for (size_t i = 0; i != str2.size(); ++i)
{
ch = str2[i];
if (ch >= '0' && ch <= '9')
is.push(ch - '0'); //减去字符0转换成int类型
else
{
switch(ch)
{
case '+':
t1 = is.top();
is.pop();
t2 = is.top();
is.pop();
t3 = t2 + t1;
is.push(t3);
break;
case '-':
t1 = is.top();
is.pop();
t2 = is.top();
is.pop();
t3 = t2 - t1;
is.push(t3);
break;
case '*':
t1 = is.top();
is.pop();
t2 = is.top();
is.pop();
t3 = t2 * t1;
is.push(t3);
break;
case '/':
t1 = is.top();
is.pop();
t2 = is.top();
is.pop();
t3 = t2 / t1;
is.push(t3);
break;
}
}
}
return is.top();
}
int main()
{
string str1, str2;
stack<char> s; //作为栈
cout << "请输入正确的表达式:";
cin >> str1;
InfixToPostfix(str1, str2, s);
cout << "转换的后缀表达式为:" << str2 << endl;
cout << "最终的值为:" << GetResult(str2) << endl;
return 0;
}
运行结果如下