简单LinuxC程序关于报数问题

xiaoxiao2021-02-28  82

题目:有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只有在记到非零的元素时才自增。
转载请注明原文地址: https://www.6miu.com/read-46598.html

最新回复(0)