用数组与循环解决约瑟夫环问题

采用数组与循环解决约瑟夫问题
菜鸟第一次写东西,有写的不好的地方各位大佬轻喷


#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值