大一初学指针第一天,作一下课后习题。(《C程序设计 第五版》 谭浩强 第八章第5题)数组
具体题目如标题所示,我首先想到用数组表示n我的,首先将前n位初始化为1,循环报数退出第3位,退出的用0表示,只剩最后一我的时输出他的位数。spa
在循环中,有这几点须要考虑:设计
1. 数到第三位时,将0赋给指针指向的数组元素。指针
2. 指针应跳过0。code
3. 指针指向最后一位后应重置到首位前。blog
因而有代码以下:io
1 #include <stdio.h> 2 #include <stdlib.h> 3 #define SIZE 1024 //最大判断人数 4 int main(){ 5 int numberLast,peopleNum,peopleExist[SIZE]={0},i; 6 int * firstPtr, * movePtr; //firstPtr指向判断数组PeopleExist的首位 7 8 puts("Enter the number of people."); 9 scanf("%d",&peopleNum); 10 11 movePtr=firstPtr=peopleExist; 12 numberLast=peopleNum; 13 //人员存在判断初始化 14 for(i=0;i<peopleNum;i++,movePtr++){ 15 *movePtr=1; 16 } 17 18 movePtr=firstPtr; 19 20 while(1){ 21 for(i=1;i<=3;i++,movePtr++){ 22 if(!(*movePtr)){ 23 i--; //跳过0 24 if(movePtr==firstPtr+peopleNum-1) movePtr=firstPtr-1; //movePtr指向数组最后一位时重置movePtr,下同 25 continue; 26 } 27 if(i==3&&*movePtr){//第三位离开 28 *movePtr=0; 29 numberLast--; 30 } 31 if(movePtr==firstPtr+peopleNum-1) movePtr=firstPtr-1; 32 } 33 if(numberLast==1) break;//只剩最后一人时跳出循环 34 } 35 36 //循环找出最后一人 37 movePtr=firstPtr; 38 while(1){ 39 if(*movePtr){ 40 printf("The last people is No.%d.\n",movePtr-firstPtr+1); 41 break; 42 } 43 movePtr++; 44 } 45 46 system("pause"); 47 return 0; 48 }
编译运行,结果以下:编译
Enter the number of people.
5
The last people is No.4.ast