简单LinuxC程序关于报数问题

来源:互联网 发布:链路状态协议网络拓扑 编辑:程序博客网 时间:2024/06/13 12:54

题目:有n个人围成一圈,顺序排号,从第一个开始报数(从1到3报数),凡报到3的人退出圈子,求出最后留下的是原来的第几号。编写一个C语言程序完成该功能,要求n从键盘输入。

源程序:
#include <stdio.h>int stay (int n){int count = n;int count2 = 0;int count3 = 0;int people[n];int i;for (i = 0;i < n; i++){people[i] = i + 1;    //给每个人排号}while (count > 1){if (people[count2] > 0)     //只有留下的人才报数{count3++;}count2++;if (count3 == 3){count--;people[count2 - 1] = 0;    //报到3的人退出count3 = 0;}if (count2 == n){count2 = 0;    //最后一个人报完数,又从第一个开始}}for (i = 0 ;i < n ;i++){if (people[i] > 0)     //不为0的即为最后留下的人{return people[i];}}return 0;}int main(){int n;printf ("input the number of people :");scanf ("%d",&n);printf ("The last people is the NO.%d\n",stay (n));    return 0;}
        本题最关键的是计数变量的使用,需要搞清每一个计数变量自增的条件,以及归零的条件。在本题中,报数的只有留下的人,所以报数的计数变量count3只有在记到非零的元素时才自增。

阅读全文
1 0