问题描述 十个人围成一圈,分别编号一到十,从一开始报数报到七的出去,继续报,问最后剩下的是原来的几号? 代码1(本问题解决方案) #include <stdio.h> #include <stdlib.h> #define LENGTH 10 //十个人 #define KEY 7 //被淘汰的编号 /* * 思路: * 用一个数组存放10个人的状态。1存货,0淘汰。 * 当只有一个人剩下,则结束。 */ int main(void) { int people[LENGTH]; int alive = LENGTH;//没有淘汰的人数 int no;//编号 int i; for (i = 0; i < LENGTH; ++i) //状态全部置1 people[i] = 1; for(no = 1,i = 1; alive !=1; ++i) {//只有剩下一个人则停止循环 if (people[i%(LENGTH + 1) - 1]) { if (no%KEY == 0) {//淘汰该人 people[i%(LENGTH + 1) -1] =0; alive--; } no++; } } for (i = 0; people[i] != 1; i++) //找出存货的人 ; printf("第%d个人存活/n", i+1); exit(0); } 代码2(代参数的灵活方案) #include <stdio.h> #include <stdlib.h> #include <assert.h> int main(int argc, char *argv[]) { int *people; int people_counts; int key_num; int alive ;//没有淘汰的人数 int no;//编号 int i; assert(argc == 3); //验证参数 assert(people_counts = atoi(argv[1])); assert(key_num = atoi(argv[2])); assert(people = (int *)malloc(people_counts * sizeof (int)));//动态分配 for (i = 0; i < people_counts; ++i) //状态全部置1 people[i] = 1; for(no = 1,i = 1, alive = people_counts; alive !=1; ++i) {//只有剩下一个人则停止循环 if (people[i%(people_counts + 1) - 1]) { if (no%key_num == 0) {//淘汰该人 people[i%(people_counts + 1) -1] =0; alive--; } no++; } } for (i = 0; people[i] != 1; i++) //找出存货的人 ; printf("第%d个人存活/n", i+1); if (people)//释放 free(people); exit(EXIT_SUCCESS); }