之前自己写了点,但是太乱了,直接看大神的吧,大神写的代码简洁而且符合所有要求,服了服了
谢谢大神了!!!
题目如下:
#include<stdio.h>
/*左搜索函数:从左至右,检索第一个目标的位置*/
int searchleft(int i,char x[20][120],char key){
int v;
for(v=0;v<120&&x[i][v]!=key;v++);
return v;
}
/*右搜索函数:从右至左,检索第一个目标的位置*/
int searchright(int i,char x[20][120],char key){
int v;
for(v=119;v>0&&x[i][v]!=key;v--);
return v;
}
/*输出函数:按格式输出每一次变化后酒窖中酒的位置*/
void output(char x[20][120],int i){
int j1,j2,j3,k;
for(j1=1;j1<=6;j1++){
for(j2=1+20*(j1-1);j2<=j1*20;j2++)
printf("%4d",j2);
printf("\n");
for(j3=0;j3<i+1;j3++)
for(j2=(j1-1)*20;j2<j1*20;j2++)
printf("%4c",x[j3][j2]);
printf("\n");
}
for(k=0;k<120;k++)
x[i+1][k]=x[i][k];
}
/*买酒函数:判断酒窖空间是否足够并在合适的位置摆上酒*/
bool buy(int m,char type,int i,char x[20][120]){
int a,b,c,d;
bool empty;
a=searchleft(i,x,type);
if(a==120){
for(b=0;b<120;b++){
empty=true;
if(x[i][b]==' '){
for(c=b;c<b+m;c++)
if(x[i][c]!=' ')
empty=false;
if(empty&&(b+m)<121){
for(d=b;d<b+m;d++)
x[i][d]=type;
return true;
}
}
}
return false;
}
else{
b=a;
empty=true;
for(c=b-1;c>=b-m;c--)
if(x[i][c]!=' ')
empty=false;
if(empty&&(b-m)>-1){
for(d=b;d>=b-m;d--)
x[i][d]=type;
printf("\n%d\n",d);
return true;
}
b=searchright(i,x,type);
empty=true;
for(c=b+1;c<=b+m;c++)
if(x[i][c]!=' ')
empty=false;
if(empty&&(b+m)<121){
for(d=b;d<=b+m;d++)
x[i][d]=type;
return true;
}
return false;
}
}
/*喝酒函数:判断酒是否足够并在合适的位置取下酒*/
bool drink(int n,char type,int i,char x[20][120]){
int a,b;
bool enough;
a=searchleft(i,x,type);
if(a==120)
return false;
else{
enough=true;
for(b=a;b<-n+a;b++)
if(x[i][b]!=type)
enough=false;
if(enough)
for(b=a;b<-n+a;b++)
x[i][b]=' ';
else
return false;
}
return true;
}
/*主函数:酒窖初始化并将调用合适的函数*/
void main(){
char x[20][120],type;
int y=1,i=0,h,k;
for(h=0;h<20;h++){
for(k=0;k<120;k++)
x[h][k]=' ';
}
while(y!=0){
printf("please input y(positive for buy,negative for drink)=");
scanf("%d",&y);
printf("please input the type of wine=");
scanf("\n%c",&type);
if(y<0){
if(drink(y,type,i,x)){
output(x,i);
i++;
}
else
printf("\nnot enough for drinking!\n\n");
}
if(y>0){
if(buy(y,type,i,x)){
output(x,i);
i++;
}
else
printf("\nno space for buying!\n\n");
}
}
printf("\n\n\n-------------------The Progrom Over!------------------\n");
}