采用数组与循环解决约瑟夫问题
菜鸟第一次写东西,有写的不好的地方各位大佬轻喷
#include <stdio.h>
int main() {
int total;//total代表总人数
int s, m;//s代表开始的人,m是淘汰数字
int count = 0;//count是每个人的淘汰判定条件
printf("please input the total number of people:");
scanf("%d", &total);
printf("please input the start number:");
scanf("%d", &s);
printf("please input the die number:");
scanf("%d", &m);
int array[total];
for (int i = 0; i < total; i++) {
array[i] = i + 1;
}//给每个人编号,但数组下标从0开始,通常情况下人的编号都是从1开始,这里就用i+1为编号开始。
int i = s - 1;//从第s个人开始,则其对应的下标为s-1
while (total > 1) {
count++;//count就是决定人是否淘汰的数字,每过一个人count要加1
if (count == m) {//如果一个人的count与淘汰编号相等,则这个人淘汰,count重新开始
printf("%d is dead\n", array[i]);//宣布淘汰人
for (int j = i; j < total - 1; j++) {//用后一项逐个覆盖前一项的方法将淘汰人从数组中删除
array[j] = array[j + 1];
}
total -= 1;
for (int num = 0; num < total; num++) {//显示当前存活的人
printf("array[%d]=%d ", num, array[num]);
}
printf("\n");
count = 0;
continue;
}
i++;
i = i % total;//在运行过程中存在一种这个环形结构,类似时钟,用取余的方法可以实现程序的正确运行
}
printf("最终%d存活", array[0]);
return 0;
}