C++猴子选大王是一个经典的问题,可以使用循环和数组来解决。以下是一个简单的C++代码实现:
```cpp
#include <iostream>
using namespace std;
int findKing(int n, int k) {
int monkeys[n];
for (int i = 0; i < n; i++) {
monkeys[i] = i + 1;
}
int currentMonkey = 0;
int count = 1;
while (n > 1) {
if (monkeys[currentMonkey] != 0) {
if (count == k) {
monkeys[currentMonkey] = 0;
count = 1;
n--;
} else {
count++;
}
}
currentMonkey = (currentMonkey + 1) % n; // 循环到下一只猴子
}
for (int i = 0; i < n; i++) {
if (monkeys[i] != 0) {
return monkeys[i];
}
}
return -1; // 返回-1表示没有找到大王
}
int main() {
int n, k;
cout << "请输入猴子的总数:";
cin >> n;
cout << "请输入每次报数的数字:";
cin >> k;
int king = findKing(n, k);
if (king != -1) {
cout << "大王是:" << king << endl;
} else {
cout << "没有找到大王" << endl;
}
return 0;
}
```
在上面的代码中,我们首先根据猴子的总数创建一个数组 `monkeys`,存储每只猴子的编号。然后,我们使用 `currentMonkey` 变量来追踪当前报数的猴子,并用 `count` 变量来计数。
在每次循环中,我们检查当前猴子是否已经被淘汰(`monkeys[currentMonkey] != 0`)。如果是,我们将继续移动到下一只猴子。如果不是,我们就检查是否达到了报数的数字 `k`。如果是,我们将当前的猴子标记为淘汰(`monkeys[currentMonkey] = 0`),同时重置计数器(`count = 1`),并将猴子总数减一(`n--`)。如果不是,我们将计数器加一。
最后,我们遍历数组找到唯一一个不为零的猴子,这就是大王。如果找到了大王,我们就打印出来;否则,我们输出“没有找到大王”。
希望以上代码对你有帮助!
制作不易,请点赞加关注