题目
解答
#include<stdio.h>
/*
循环数组的使用:
假设数组元素个数n为10,元素为a[0]~a[9]
初始位置为pos,向后移动k位后:pos=(pos+k)%n
1、保证了数组下标每个空间都被充分利用
2、元素个数n=数组最大下标+1,保证了最大下标取余数时不会变成0
正确的:假设n=10,数组最大下标=9,则:9%10=9,10%10=0
错误的:假设n=10,数组最大下标=10,则:10%10=0
*/
//将狼找过的洞标为0
void algo(int a[],int n){
int i,pos; //i是狼找的次数,pos是狼找的洞的位置
for(i=1,pos=0;i<=100;i++){//假设狼找了100次都没找到
a[pos]=0; //数组下标从0开始
pos=(pos+i+1)%n; //狼位置pos的变化规律
}
}
void main(){
int i,n=10,a[10];
for(i=0;i<n;i++) //将洞初始化为1
a[i]=1;
algo(a,n);
for(i=0;i<n;i++){
if(a[i])
printf("兔子可能在第%d洞中\n",i+1);
}
}