关于学生报数的问题, 怎么看自己的程序都觉得没问题,到底错在哪了?

hendin 2007-10-27 11:27:27
题目是这样的:若干学生按学号从小到大(1,2,3,4...)顺序围成一圈,从学号1的学生开始报数,每报到数值为n的同学离开,从下一学生开始继续报数,报到n的同学又离开,以此类推,求最后一个留下的同学的学号.

下面是我自己写的程序,运行时总是有错误,怎么看都没觉得有什么问题,请大家帮忙改改,谢谢!


#define SIZE 16
main(){
int array[SIZE],n=SIZE,i,cont;
void baoshu();
for( i=0;i<SIZE;i++)
array[i]=i+1;
printf("input the counter:\n");
scanf("%d",&cont);
baoshu(array,n,cont);
getch();
}

/*用一数组代表围成圈的学生,数组初始化时分别按号数赋值1,2,3...,top指向第一个学生,
bot指向最后一个,用head指向下一轮开始报数的学生,cont为报数值*/
void baoshu(int arr[],int n,int cont){
int *top, *bot,*head,i,counter;
head=top=arr;bot=&arr[n-1];

while(top!=bot)
{ counter=1;
while(counter<cont){ /*每一轮的报数*/
if(head==bot)
{head=top;counter++;continue;}
if(*(++head)!=0) counter++;
}
*head=0; /*报到报数值的学生离开,赋予0*/

for(i=0;i<n;i++){ /*修改top定位*/
if(arr[i]!=0){top=&arr[i];break;}}

for(i=n-1;i>=0;i--) /*修改bot定位*/
{if(arr[i]!=0)
{bot=&arr[i];break;}}

while(*(++head)==0) /*修改head定位*/
{if(head==bot)
{head=top;break;}
}

}
printf("the lase one is %d\n",*top);

}
...全文
98 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
Seaside_Boy 2007-10-27
  • 打赏
  • 举报
回复
还有一个,要修改head定位这段函数,改为:
while(head!=&arr[n-1]&&*(++head)==0) /*修改head定位*/
{
if(head==bot)
{
head=top;
break;
}
}
if(head==&arr[n-1])
head=top;
hendin 2007-10-27
  • 打赏
  • 举报
回复
谢谢,不过我美有用到库函数,而且声明函数时不写形参也是可以的.
hendin 2007-10-27
  • 打赏
  • 举报
回复
谢谢,不过我美有用到库函数,而且声明函数时不写形参也是可以的.
zhdm_xj 2007-10-27
  • 打赏
  • 举报
回复
1.#include "stdio.h"
2.void baoshu(); ->void baoshu(int arr[],int n,int cont);
huangxw000 2007-10-27
  • 打赏
  • 举报
回复
学习中
hendin 2007-10-27
  • 打赏
  • 举报
回复
楼上的,高手啊,谢谢,原来修改bot定位后没有考虑到head指针可能跑到bot后面去了!
把/*修改head定位*/的一段程序修改成以下也可以,真非常感谢!搞定了!

if(head>bot) head=top; /*修改head定位*/
else while(*head==0) head++;

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧