题目:![](https://img-blog.csdnimg.cn/c838edaa8de141b49c82db0366d536b0.png)
先设n=8,将题目抽象成8个人在酒桌上喝酒,每报到3的人out,然后报数归0,下一个人从1开始报数,以此类推,out顺序为3,6,1,5,2,8,4,7如下图所示。
![](https://img-blog.csdnimg.cn/44925909d624424e94359b58fa241e12.png)
![](https://img-blog.csdnimg.cn/3a52c5c9e031449abc07c57942856897.png)
![](https://img-blog.csdnimg.cn/016fcd506b894fbc9d8cbe370588fc0a.png)
![](https://img-blog.csdnimg.cn/75c975fa3cb94031b21359fc6e376b41.png)
![](https://img-blog.csdnimg.cn/e2d3fa8838e1434bb610d38e6e650c71.png)
![](https://img-blog.csdnimg.cn/d7d999d91edb4644974a266c5348f07b.png)
![](https://img-blog.csdnimg.cn/66d56ff6f2c54615a3aea3ab6ec9987b.png)
再将大问题分解为几个小问题:
1、8个人该如何存储?
C语言中,存储数据只有两种方法:数组、结构体
没有特征的就选【数组】,有年龄,身高的等特征的选【结构体】
这里这需要存8个人,故选数组。
2、报数问题:只需要用int baoshu来解决
3、如何表示清醒还是醉了:table[index]=1;table[index]=0表示醉了
4、表示目前还在桌的:count;
通过以上变量就基本可以实现这个问题的程序了。
此为VS2013:其余版本去除getchar();
#include<stdio.h>
int main()
{
int table[100] = { 1, 1, 1, 1 };//1是醒着的,0是喝醉的
for (int i = 1; i <= 8; i++)
{
table[i] = 1;//先让8个人都清醒
}
for (int i = 1; i <= 8; i++)
{
printf("%-4d", table[i]);
}
printf("\n");
int index;
int baoshu;
int count = 8;
index = 0;
baoshu = 0;//赋初始值
while (count > 0)
{
index++;//刚进入循环就变1
baoshu++;//只会123循环
while (table[index] == 0)//判断有没有喝醉的。若没有则跳出while
{
index++;//若他醉了则后移一位//4,7,2,6,3,9,5,8,5
if (index > 8)/*注意:在前5次循环时,不经过if。因为index只有8个,当index大于8时就会重新赋值为1;*/
{
index = 1;
}
}
if (baoshu == 3)
{
table[index] = 0;//如果报数的等于3,那么index=0(他醉了)
printf("%-4d", index);//输出他
count--;//在场醒的人减1
baoshu = 0;//报数重置
}
}
getchar();
return 0;
}
输出 结果:6个1为在场人数
3,6,1,5,2,8,4,7为依次喝醉的人