2 1.000+2/4= ((1+2)*5+1)/4=
1.50 4.00
AC码:
#include<stdio.h>
#include<string.h>
char str[3000];
int t;
double eval()
{
double x=0,m;
if(str[t]==‘ ‘)
t--;
if(str[t]==‘+‘)
{
t--;
return eval()+eval();
}
if(str[t]==‘-‘)
{
t--;
return eval()-eval();
}
if(str[t]==‘*‘)
{
t--;
return eval()*eval();
}
if(str[t]==‘/‘)
{
t--;
return eval()/eval();
}
while(str[t]>=‘0‘&&str[t]<=‘9‘)
{
x=x*10+str[t]-‘0‘;
t--;
}
if(str[t]==‘.‘)
{
t--;
m=0.1;
while(str[t]>=‘0‘&&str[t]<=‘9‘)
{
x=x+(str[t]-‘0‘)*m;
m=m*0.1;
t--;
}
}
return x;
}
int main()
{
int top,count,T,len,i;
char ch[1005],pt[1000];
scanf("%d",&T);
while(T--)
{
scanf("%s",ch);
len=strlen(ch);
top=-1;
memset(pt,0,sizeof(pt));
count=-1;
for(i=len-2;i>=0;i--)
{
if(ch[i]>=‘0‘&&ch[i]<=‘9‘)
{
while(ch[i]==‘.‘||(ch[i]>=‘0‘&&ch[i]<=‘9‘))
{
top++;
str[top]=ch[i];
i--;
}
top++;
str[top]=‘ ‘;
}
if(i<0)
break;
if(ch[i]==‘)‘)
{
count++;
pt[count]=ch[i];
}
else if(ch[i]==‘(‘)
{
while(count>=0&&pt[count]!=‘)‘)
{
top++;
str[top]=pt[count];
count--;
top++;
str[top]=‘ ‘;
}
count--;
}
else if(ch[i]==‘*‘||ch[i]==‘/‘)
{
count++;
pt[count]=ch[i];
}
else
{
while((pt[count]==‘*‘||pt[count]==‘/‘)&&count>=0&&pt[count]!=‘)‘)
{
top++;
str[top]=pt[count];
top++;
str[top]=‘ ‘;
count--;
}
count++;
pt[count]=ch[i];
}
}
// printf("%d\n",count);
while(count>=0)
{
if(pt[count]!=‘)‘)
{
top++;
str[top]=pt[count];
top++;
str[top]=‘ ‘;
count--;
}
}
str[top]=‘\0‘;
//printf("%s\n",str);
t=strlen(str)-1;
printf("%.2f\n",eval());
}
return 0;
}原文地址:http://blog.csdn.net/u012804490/article/details/24704785