|
20鱼币
用C语言实现的舞伴配对问题,为什么会无限循环?
#include<stdio.h>
#include<stdlib.h>
#define size 50
typedef struct
{
char name[20];
char male;
}people;
typedef struct
{
people* ren;
int front,rear;
}S;
void init(S* st)
{
st->ren=(people *)malloc(size*sizeof(people));
st->front=st->rear=0;//初始化顺序栈
}
int full(S* st)//判断队列是否满
{
if(((st->rear)+1)%size==st->front)
return 1;
return -1;
}
int empty(S* st)//判断队列是否为空
{
if(st->rear==st->front)
return -1;
else return 1;
}
int enter(S* st,people person)//插入元素
{
if(full(st))
{
printf("队列已满\n");
return 1;
}
st->ren[st->rear]=person;
st->rear=(st->rear+1)%size;
return -1;
}
int pop(S* st,people* person)
{
if(!empty(st))
{
printf("空\n");
return -1;
}
*person=st->ren[st->front];
st->front=(st->front+1)%size;
return 1;
}
people gethead(S Q)
{//返回Q的队头元素,不修改队头指针
if(Q.front!=Q.rear) //队列非空
return Q.ren[Q.front]; //返回队头元素的值,队头指针不变
}
void dance(people dancers[],int n)
{
S man,woman;
people person;
init(&man);
init(&woman);
int i;
for(i=0;i<n;i++)
{
if(dancers[i].male=='F')
{
enter(&woman,dancers[i]);
}
if(dancers[i].male=='M')
{
enter(&man,dancers[i]);
}
else
printf("性别输入错误:%s %c\n",dancers[i].name,dancers[i].male);
}
printf("舞伴配对如下\n");
while(empty(&man)&&empty(&woman))
{
pop(&woman,&person);
printf("%s女士与",person.name);
pop(&man,&person);
printf("%s男士配对\n",person.name);
}
if(empty(&man))
{
person=gethead(man);
printf("%s男士将在下一轮第一个获得匹配机会\n",person.name);
}
if(empty(&woman))
{
person=gethead(woman);
printf("%s女士将在下一轮第一个获得匹配机会\n",person.name);
}
}
int main()
{
int n,i;
people wuzhe[size];
printf("请输入等待的总人数\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("请输入第%d位舞者的姓名和性别,用空格隔开(F表示女,M表示男)\n",i+1);
scanf("%s %c",&wuzhe[i].name,&wuzhe[i].male);
}
dance(wuzhe,n);
return 0;
}
感谢 |
最佳答案
查看完整内容
队列满和队列空的判断逻辑问题:full 函数返回 1 表示满,但是判断条件应返回非0值表示真(在 C 中常用),return -1 会被认为是假,这与预期相反。
empty 函数逻辑也是反的,return -1 表示队列为空时实际应返回真(1),但返回了假(-1)。
pop 函数中的逻辑错误:在检查队列是否空时,empty(st) 应该返回 1 时表示空,但是您的代码中使用了 !empty(st) 表示队列为空。
男女判断和性别输入错误处理逻辑错误:当性别为男( ...
|