//author: ***
//course designing for data structures and program design in c++
//time:***
/*
a simulant calculator
description: requiring design a simulant calculator ,which could take operations such as +,-,*,/ ,( ),or functon SQR ,ABS
condition:inputted expression can limit into int type.therefore ,you must check the expression for exactness.if the errors
take place ,the program would give an alarm.
*/
#include
#include
#include
#include
#include
#include
using namespace std;
void init(string& s)
{
cout<<"enter the expression:";
cin>>s;
s+="#";
}
void error(int tag)
{
switch(tag)
{
case 1:
cout<<"wrong operator!"<
case 2:
cout<<"wrong operand!"<
}
}
bool is_optr(char c)
{
string optr_string("+-*/()AS#");
for(int i=0;i
return true;
return false;
}
char precede(char op1, char op2)
{
string tab[9];
tab[0]=">><<<><<>";
tab[1]=">><<<><<>";
tab[2]=">>>><><<>";
tab[3]=">>>><><<>";
tab[4]="<<<<<=<
tab[6]=">>>><>>>>";
tab[7]=">>>><>>>>";
tab[8]="<<<<
int op1_loc,op2_loc;
for(op1_loc=0;op1_loc
for(op2_loc=0;op2_loc
return tab[op1_loc][op2_loc];
}
double operate(double x,char op,double y)
{
switch(op)
{
case '+': return x+y; break;
case '-': return x-y; break;
case '*': return x*y; break;
case '/': return x/y; break;
case 'A': return fabs(y);break;
case 'S': return sqrt(y);break;
}
return -1;
}
double cal(string& s)
{
stack
optr.push('#');
stack
char c=s[0];
s.erase(0,1);
while(c!='#'||optr.top()!='#')
{
if(!is_optr(c))
{
if(c>='0'&&c<='9')
{
string num;
num.insert(num.begin(),c);
int loc=0;
while(!is_optr(s[loc]))
loc++;
string num2(s,0,loc);
num+=num2;
s.erase(0,loc);
double x=atof(num.c_str());
opnd.push(x);
c=s[0];
s.erase(0,1);
}
else { error(2); return -1;}
}
else
{
switch(precede(optr.top(),c))
{
case '<': optr.push(c); c=s[0]; s.erase(0,1); break;
case '=': optr.pop(); c=s[0]; s.erase(0,1); break;
case '>':
char op;
op=optr.top();
optr.pop();
double a,b;
a=opnd.top();
opnd.pop();
if(op!='S'&&op!='A')
{
b=opnd.top();
opnd.pop();
}
double res;
res=operate(b,op,a);
opnd.push(res);
break;
case 'E':
error(1);
return -1;
}
}
}
return opnd.top();
}
int main()
{
string expression;
double value;
init(expression);
value=cal(expression);
cout<
return 0;
}