比较简单,只支持0-9的加减乘除和括号运算,有机会再改进
// 四则运算1.0
// 支持0-9的加减乘除计算
#include <iostream>
#include <stack>
#include <string>
#include <cstring>
#include <cctype>
#include <cstdlib>
using namespace std;
string infixToPostfix(string exp);
bool calculator(string postfix);
float ans;
int main()
{
string expression;
cout << "Enter a expression <quit to quit>: ";
while(cin >> expression && expression != "quit")
{
string postfix = infixToPostfix(expression);
if(postfix == "error")
{
cout << "Incorrect expressions. Please input again <quit to quir>: ";
continue;
}
else
{
cout << "postfix is : " << postfix << endl;
if(calculator(postfix))
cout << ans << endl;
else
{
cout << "Incorrect expressions. Please input again <quit to quir>: ";
continue;
}
}
cout << "Enter a expression <quit to quit>: ";
}
cout << "Done!\n";
return 0;
}
// 将后缀表达式转换为中缀表达式
string infixToPostfix(string exp)
{
stack<char> st;
string postfix;
for(auto s : exp)
{
if(isdigit(s))
{
postfix.append(1, s);
}
else if(s == '+' || s == '-')
{
if(!st.empty() && (st.top() == '*' || st.top() == '/'))
{
while(!st.empty() && st.top() != '(')
{
postfix.append(1, st.top());
st.pop();
}
}
st.push(s);
}
else if(s == '*' || s == '/')
{
st.push(s);
}
else if(s == '(')
{
st.push(s);
}
else if(s == ')')
{
while(st.top() != '(')
{
postfix.append(1, st.top());
st.pop();
}
st.pop();
}
else
return "error";
}
while(!st.empty())
{
postfix.append(1, st.top());
st.pop();
}
return postfix;
}
// 利用中缀表达式计算结果
bool calculator(string postfix)
{
ans = 0.0;
stack<float> st;
for(auto s : postfix)
{
if(isdigit(s))
{
float a = s - 48;
st.push(a);
}
else
{
float a = st.top();
st.pop();
float b = st.top();
st.pop();
switch(s)
{
case '+':
ans = a + b;
st.push(ans);
break;
case '-':
ans = b - a;
st.push(ans);
break;
case '*':
ans = a * b;
st.push(ans);
break;
case '/':
if(a != 0)
{
ans = b / a;
st.push(ans);
}
else
return false;
break;
}
}
}
return true;
}