3+5*(4+8)/2 是一个字符串
// 感谢网友nasi00(莫傲·逍遥)提供代码
#include <iostream>
using namespace std;
#include <stack>
#include <string>
#include <cstdlib>
void init(string& s)
{
getline(cin,s);
s+="@";
}
bool is_optr(char c)
{
string optr_list("+-*/()@");
for(int i=0;i<optr_list.size();i++)
if(c==optr_list[i])
return true;
return false;
}
char first(char op1, char op2)
{
string tab[7];
tab[0]=">><<<>>";
tab[1]=">><<<>>";
tab[2]=">>>><>>";
tab[3]=">>>><>>";
tab[4]="<<<<<=E";
tab[5]=">>>>E>>";
tab[6]="<<<<<E=";
string optr_list("+-*/()@");
int op1_loc, op2_loc;
for(op1_loc=0;op1_loc<optr_list.size();op1_loc++)
if(optr_list[op1_loc]==op1)
break;
for(op2_loc=0;op2_loc<optr_list.size();op2_loc++)
if(optr_list[op2_loc]==op2)
break;
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;
}
return -1;
}
double calc(string& s)
{
stack<char> optr;
optr.push('@');
stack<double> opnd;
char c=s[0];
s.erase(0,1);
while( c!='@' || optr.top()!='@' ) {
if( !is_optr(c) ) {
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 {
switch( first(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();
b=opnd.top();
opnd.pop();
double res;
res=operate(b,op,a);
opnd.push(res);
break;
}
}
}
return opnd.top();
}
int main()
{
string exp;
double ans;
init(exp);
ans=calc(exp);
cout<<ans<<endl;
return 0;
}