这个表达式计算不出来emmm 2/(1+2+6/6/2-2)(8/2/2)
适用于 一位数的计算±//*()
代码还不够完善,希望可以写全面各种类型的计算器
每次写这个都卡壳,,,希望这次写好一些
#include<iostream>
#include<string>
#include<stack>
using namespace std;
class calculator
{
private:
string formula;
stack<int>num;
stack<char>op;
public:
calculator()
{
while(!num.empty())
{
num.pop();
}
while(!op.empty())
{
op.pop();
}
}
~calculator()
{
while(!num.empty())
{
num.pop();
}
while(!op.empty())
{
op.pop();
}
formula="";
}
bool input()
{
cin>>formula;
if(formula=="END")
{
return false;
}
else return true;
}
void result();
void cal();
};
void calculator::cal()
{
int n=formula.length();
int i;
for(i=0;i<n;i++)
{
if(formula[i]>='0'&&formula[i]<='9')
{
num.push(formula[i]-'0');
}
else if(formula[i]=='+'||formula[i]=='-')
{
while(!op.empty()&&op.top()!='(')
{
result();
}
op.push(formula[i]);
}
else if(formula[i]=='(')
{
op.push(formula[i]);
}
else if(formula[i]==')')
{
while(op.top()!='(')
{
result();
}
op.pop();
}
else if(formula[i]=='*'||formula[i]=='/')
{
if(op.empty()==true||op.top()=='+'||op.top()=='-'||op.top()=='(')
{
op.push(formula[i]);
}
else
{
while(op.top()=='*'||op.top()=='/')
{
result();
}
op.push(formula[i]);
}
}
}
while(!op.empty())
{
result();
}
cout<<num.top()<<endl;
}
void calculator::result()
{
int l,r,res;
r=num.top();
num.pop();
l=num.top();
num.pop();
char c=op.top();
op.pop();
if(c=='+')
res=r+l;
else if(c=='-')
res=l-r;
else if(c=='*')
res=l*r;
else if(c=='/')
res=l/r;
num.push(res);
}
int main()
{
calculator test;
while(test.input())
{
test.cal();
}
return 0;
}