谭浩强C++课后习题26——报数游戏

谭浩强C++课后习题26——报数游戏

题目描述:有n个人围成一圈,顺序排号。从第一个人开始报数(从1~3报数),凡报到3的人退出圈子,问最后留下来的人原来排在第几号。

算法思路:定义一个数组person并对其进行初始标号,定义一个i用于数组下标的标记,temp用于报数,count表示退出人数,当退出人数为n-1个时(即只剩一个人没有退出)结束循环,如果i标号处的数组值不为0(即该标号处的人还没退出),则报数标记temp自增,如果temp等于3则另该出的数组值为0(拟退出),令temp重新报数(temp=0),退出的人数加1;如果i自增后为n,即超过数组长度,另i=0继续循环。最后打印剩下一个数组值不为0的。

#include<iostream>
using namespace std;
int main() {
	int n;
	cout << "输入人数:";
	cin >> n;
	int* person = new int[n];
	for (int i = 0;i < n;i++)
		person[i] = i + 1;
	int i = 0, temp = 0, count = 0;
	while (count < n - 1) {
		if (person[i] != 0)
			temp++;
		if (temp == 3) {
			person[i] = 0;
			temp = 0;
			count++;
		}
		i++;
		if (i == n)
			i = 0;
	}
	for (int j = 0;j < n;j++) {
		if (person[j] != 0)
			cout << "剩下的人是:" << person[j] << endl;
	}
	return 0;
}

运行测试结果:
在这里插入图片描述

发布了35 篇原创文章 · 获赞 35 · 访问量 581

猜你喜欢

转载自blog.csdn.net/weixin_45295612/article/details/105290347