您的位置:首页 > 其它

(精)河南省第4届acm(表达式求值)

2012-05-03 13:54 323 查看
一个break引发的血案,开始的时候我一直找不到哪里错误了,后来的时候,我才发现,如果第一个是数字的话,直接回跳出while。
应该改成continue
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<stack>
#include<math.h>
#define MAX 1000
using namespace std;

int max(int a,int b)
{
if(a>b)
{
return a;
}
return b;
}

int min(int a,int b)
{
if(a<b)
{
return a;
}
return b;
}

int add(int a,int b)
{
return a+b;
}

int getnum(char temp[])
{
int i=0;int result=0;

//反转
char tempfan[MAX];
for(i=0;i<strlen(temp);i++)
{
tempfan[strlen(temp)-i-1]=temp[i];
}
tempfan[i]='\0';

for(i=0;i<strlen(temp);i++)
{
result+=pow(10,i)*(tempfan[i]-'0');
}
return result;
}
int main()
{
//freopen("in.txt","r",stdin);
int casen;
scanf("%d",&casen);
while(casen--)
{
//输入
char str[350];scanf("%s",str);

//开会处理
stack<int>num;//数字栈
stack<string>function;//函数栈

//如果直接就是一个数字,输出,让后结束
if(str[0]>='0'&&str[0]<='9')
{
cout<<getnum(str)<<endl;
continue;
}

//
int i=0;
while(i<strlen(str))
{
//数字------------------------------------------------------------------------------数字
if(str[i]>='0'&&str[i]<='9')
{
char temp[MAX];int tempkey=0;

//保存第一个数
char tempchar=str[i];
temp[tempkey]=tempchar;tempkey++;i++;

//把剩余的数字也存贮起来
while(str[i]>='0'&&str[i]<='9')
{
//保存数字
tempchar=str[i];
temp[tempkey]=tempchar;tempkey++;i++;
}

temp[tempkey]='\0';
int cunchu=getnum(temp);
num.push(cunchu);

}
//数字------------------------------------------------------------------------------数字

//函数------------------------------------------------------------------------------函数
else if(str[i]>='a'&&str[i]<='z')
{
char fun[4];
fun[0]=str[i];i++;fun[1]=str[i];i++;fun[2]=str[i];i++;
i++;//跳过(
fun[3]='\0';
function.push(fun);//压入函数堆栈

}
//函数------------------------------------------------------------------------------函数

//逗号------------------------------------------------------------------------------逗号
else if(str[i]==',')
{
i++;
}
//逗号------------------------------------------------------------------------------逗号

//右括号---------------------------------------------------------------------------右括号
else if(str[i]==')')
{
i++;

//处理
string fun;
fun=function.top();function.pop();//取出函数名
int a,b;
a=num.top();num.pop();b=num.top();num.pop();//取出数字

int cunchu;
if(!fun.compare("max"))
{
cunchu=max(a,b);
}
else if(!fun.compare("min"))
{
cunchu=min(a,b);
}
else
{
cunchu=add(a,b);
}

num.push(cunchu);

}
//右括号---------------------------------------------------------------------------右括号

}//while

cout<<num.top()<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: