有个地方要注意,就是读取过程中计算完某一轮后,应该检查能否继续计算,否则会出错
#include<stdio.h>
#include<string>
bool cmp(char a,char b)
{
if(a=='*'||a=='/')return true;
if(b=='*'||b=='/')return false;
else return true;
}
double cpt(double a,double b,char o)
{
if(o=='+')return a+b;
if(o=='-')return a-b;
if(o=='*')return a*b;
return a/b;
}
int main()
{
char s[800],op[101],o,c;
double num[101],n1,n2;
int o_top,n_top;
int i,temp,l;
while(gets(s)&&strcmp(s,"0")!=0)
{
l=strlen(s);o_top=n_top=0;
for(temp=i=0;i<=l;i++)
{
if(s[i]>='0'&&s[i]<='9')temp=temp*10+s[i]-'0';
else if(s[i]!=' ')
{
num[n_top++]=temp;
temp=0;
if(s[i]!='\0')//+ - * /
{
if(o_top==0||!cmp(op[o_top-1],s[i]))op[o_top++]=s[i];
else if(cmp(op[o_top-1],s[i]))
{
n2=num[--n_top];n1=num[--n_top];
o=op[--o_top];
num[n_top++]=cpt(n1,n2,o);
op[o_top++]=s[i];
while(o_top>1&&cmp(op[o_top-2],op[o_top-1]))
{
n2=num[--n_top];n1=num[--n_top];
c=op[--o_top];
o=op[--o_top];
num[n_top++]=cpt(n1,n2,o);
op[o_top++]=c;
}
}
}
}
}
while(o_top>0)
{
n2=num[--n_top];n1=num[--n_top];
o=op[--o_top];
num[n_top++]=cpt(n1,n2,o);
}
printf("%.2lf\n",num[n_top-1]);
}
return 0;
}