# C，C++，python实现约瑟夫生者死者小游戏

2020/12/08 11:37

30人在一条船上，超载，需要15人下船，于是人们排成了一队，排队的位置即为他们的编号，从第一个开始报数，从1数到9，数到9的人下船，如此循环往复，直到船上仅剩下15人为止，那么有哪些人下船呢？
1.用C语言实现：

#include<stdio.h>

int c = 0;
int i = 1;
int j = 0;
int a[30] = {

0 };
int b[30] = {

0 };

int main()
{

while (i<=31)
{

if (i == 31)
{

i = 1;
}
else if (c == 15)
{

break;
}
else
{

if (b[i] != 0)
{

i++;
continue;
}
else
{

j++;
if (j != 9)
{

i++;
continue;
}
else
{

b[i] = 1;
a[i] = j;
j = 0;
printf("第%d号下船了\n", i);
i++;
c++;
}
}
}
}
}

2.用**C++**实现：

#include<iostream>
using namespace std;

int c = 0;
int i = 1;
int j = 0;
int a[30] = {

0 };
int b[30] = {

0 };

int main()
{

while (i<=31)
{

if (i == 31)
{

i = 1;
}
else if (c == 15)
{

break;
}
else
{

if (b[i] != 0)
{

i++;
continue;
}
else
{

j++;
if (j != 9)
{

i++;
continue;
}
else
{

b[i] = 1;
a[i] = j;
j = 0;
cout<<"第%d号下船了\n"<< i;
i++;
c++;
}
}
}
}
}

python实现

people = {

}
for i in range(1,31):
people[i] = 1

check = 0
i = 1
j = 0
while i <= 31:
if i == 31:
i = 1
elif j == 15:
break
else:
if people[i] == 0:
i += 1
continue
else:
check += 1
if check == 9:
people[i] = 0
check = 0
print("{}号下船了！".format(i))
j+=1
else:
i+=1
continue

0
0 收藏

0 评论
0 收藏
0