愿我们能与最好的自己相遇。
#include<iostream>
#include<stack>
#include<cstring>
using namespace std;
stack<int> OPND;
stack<char> OPRT;
int precede(char x);
void operate();
int calculate(string s);
int main()
{
string str;
printf("\t\t--------------------------------------------\n");
printf("\t\t--------------双栈实现简易计算器------------\n");
printf("\t\t------------------欢迎您使用----------------\n");
printf("\t\t| 计算器 |\n");
printf("\t\t| ---------------- |\n");
printf("\t\t| | | |\n");
printf("\t\t| ---------------- |\n");
printf("\t\t| 1 2 3 + |\n");
printf("\t\t| 4 5 6 - |\n");
printf("\t\t| 7 8 9 * |\n");
printf("\t\t| 0 ( ) / |\n");
printf("\t\t--------------------------------------------\n");
printf("\t\t 请输入一个用#开头和结尾的表达式:\n");
cin>>str;
calculate(str);
getchar();
getchar();
return 0;
}
//运算符优先级判断
int precede(char x)
{
if (x == '+' || x == '-')
return 0;
else if (x == '*' || x == '/')
return 1;
else if (x == '(' || x == ')')
return -1;
else if (x == '#')
return -2;
}
//二元运算
inline void operate(char top)
{
int a = OPND.top();
OPND.pop();
int b = OPND.top();
OPND.pop();
int c;
if (top == '+')
{
b += a;
OPND.push(b);
}
else if (top == '-')
{
b -= a;
OPND.push(b);
}
else if (top == '*')
{
b *= a;
OPND.push(b);
}
else if (top == '/')
{
b /= a;
OPND.push(b);
}
}
//读取表达式
int calculate(string s)
{
int a,b;
char top;
for(int i = 0;i<s.size();++i)
{
//判断是否为数字
if(isdigit(s[i]))
{
int num = 0;
string number;
number += s[i];
while(isdigit(s[++i]))
{
number += s[i];
}
for( int j=0;j<number.size();j++)
{
num = num*10 +number[j] - 48;
}
OPND.push(num);
number.clear();
}
//对操作符的操作
if(!isdigit(s[i]))
{
if(OPRT.empty())
{
OPRT.push(s[i]);
}
else
{
top = OPRT.top();
if(precede(s[i])>precede(top) || s[i] == '(')
{
OPRT.push(s[i]);
}
else
{
while(precede(s[i])<=precede(top))
{
if(top=='#'&&s[i]=='#')
{
OPRT.pop();
int ans = OPND.top();
cout<<"The answer is :"<<ans<<endl;
OPND.pop();
return 0;
}
else if(top=='('&&s[i]==')')
{
++i;
}
else
{
operate(top);
}
OPRT.pop();
top = OPRT.top();
}
OPRT.push(s[i]);
}
}
}
}
}