輸出結果
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5SMzMjZ1QmZiFTZ3MWOmJWYhFGN0ATOwEjYmFmZ4I2N08CX5d2bs92Yl1iclB3bsVmdlR2LcNWaw9CXt92Yu4GZjlGbh5yYjV3Lc9CX6MHc0RHaiojIsJye.png)
實作代碼
#include<iostream> //頭檔案,識别大部分預處理指令,編譯器才會合法識别後邊使用的關鍵字
using namespace std; //T1、命名空間,包括cout、cin、endl等
/*
函數的嵌套:約瑟夫環問題——n隻猴子選猴王的問題
}
*/
//void可知,此函數沒有使用傳回值
void NextPosition(int &p,int tail) //p是目前猴子的下标,執行函數之後得到下一個下标,tail表示最後一隻猴子的下标
{
p = (p < tail ? p + 1 : 0); //暫時不考慮被淘汰掉的猴子
int NextNumber(int n, int tail) //目前要報的數字、要報的最大數字
return n == tail ? 1 : n + 1; //
int MonkeyKing(int total, int cycle) //參數輸入猴子總數、所報最大數字
bool*failure = new bool[total]; //建立total隻猴子,為bool型,識别為是否被淘汰
memset(failure, 0, sizeof(bool)*total); //所有猴子初始化為0即false,即沒有被淘汰
//menset函數對數組進行歸0,如果要統一賦其他值,可用for循環
int position = total - 1; //目前位置确定為最後一隻猴子,
int said = 0; //所報數字
int i;
int remained = total; //剩下的猴子個數
while (remained > 1)
{
NextPosition(position,total-1); //從目前猴子移動到下一隻去
if (failure[position] = false) //假如該猴子尚未被淘汰
{
said = NextNumber(said, cycle); //被輪到的猴子應該報到的數
cout << "第" << position + 1 << "隻猴子報" << said;
if (said==cycle) //判斷這隻猴子報出的數是否為最大值,如果是,則要将其淘汰
{
failure[position] = true; //将這隻猴子淘汰出去
cout << ",被淘汰。剩下" << --remained << "個\n";
}
else cout<<"。\n";
}
}
//for (int i = 0; i < total; i++) if (failure[i] == false) break; //T1、判斷猴子是不是沒有被汰淘
for (i = 0; failure[i]; i++); //T2、最簡單的一句話
delete []failure;
return i; //傳回沒有被淘汰的猴子下标
// void return; int return 0;
void main()
cout << "Hello,world!歡迎來到《一個處女座程式猿》的部落格!\n";
int total,cycle; //定義猴子總數、所報最大數字
cout <<"請輸入猴子總數:"; // << endl
cin >> total;
cout << "請輸入猴子所報最大數:" ;
cin >> cycle;
cout << "第" << MonkeyKing(total, cycle)+1 <<"個猴子是猴王。\n";
system("pause");
return;