这是一个用stack做的表达式计算器
源代码如下:
#include<bits/stdc++.h>
#define ll long long
using namespace std;
stack<int>num;//数字栈
stack<char>op;//符号栈
int h(char a)//运算优先级
{
if(a=='(')return 0;//None
else if(a=='+'||a=='-')return 1;
else if(a=='*'||a=='/')return 2;
else return 3;//^
}
void calc()//求值
{
ll int a=num.top();//第二个操作数
num.pop();
ll int b=num.top();//第一个操作数
num.pop();
char p=op.top();//运算符
op.pop();
ll int r=0;//结果
//计算结果
if(p=='+')r=b+a;
if(p=='-')r=b-a;
if(p=='*')r=b*a;
if(p=='/')r=b/a;
if(p=='^')r=pow(b,a);
num.push(r);//结果入栈
}
int main()
{
cout<<"-----------------------------------------------------------------\n";
cout<<"| |\n";
cout<<"| Welcome to my calc. |\n";
cout<<"| You can input an expression like this: