5接着按上面的写报3的剔除,复制代码修改即可。
bs = j = 0;
while (j<n){ if (aa[j])++bs; if (bs == 3){ aa[j] = 0; bs = 0; }++j; }
j = 0; while (j < n)if (aa[j])cout << aa[j++] << ends; else ++j; cout << endl;
输出查看是否正常运行结果
6写一个结束变量用于按题目结束剔除。
int js=0;
while(1)//把上面2个剔除循环复制过来,写一个结束判断。
{
bs = j =js= 0;
while (j<n){ if (aa[j])++bs,++js; if (bs == 2){ aa[j] = 0; bs = 0; --js;}++j; }
j = 0; while (j < n)if (aa[j])cout << aa[j++] << ends; else ++j; cout << endl;
if (js <= 3)break;
bs = j =js= 0;
while (j<n){ if (aa[j])++bs,++js; if (bs == 3){ aa[j] = 0; bs = 0; --js;}++j; }
j = 0; while (j < n)if (aa[j])cout << aa[j++] << ends; else ++j; cout << endl;
if (js <= 3)break;
}
观察输出是否正确运行
图片附件: 游客没有浏览图片的权限,请
登录 或
注册
7最后整理一下代码就可以结束本题的编程了。
void 士兵队列训练()
{//缘由
https://bbs.bccn.net/redirect.php?tid=499026&goto=lastpost#lastpost
int aa[100]{0}, n = 0, j = 0, bs = 0, js = n;
cout << "输入数量" << endl; cin >> n;
while (j < n)aa[j] = 1 + j++;
j = 0; while (aa[j])cout << aa[j++] << ends; cout << endl;
while (1)
{
bs = j = js = 0;
while (j < n){ if (aa[j])++bs, ++js; if (bs == 2){ aa[j] = 0; bs = 0; --js; }++j; }
if (js <= 3)break;
bs = j = js = 0;
while (j<n){ if (aa[j])++bs, ++js; if (bs == 3){ aa[j] = 0; bs = 0; --js; }++j; }
if (js <= 3)break;
}
j = 0; while (j < n)if (aa[j])cout << aa[j++] << ends; else ++j; cout << endl;
}
8优化代码
void 士兵队列训练()
{//缘由
https://bbs.bccn.net/redirect.php?tid=499026&goto=lastpost#lastpost
int aa[100]{0}, n = 0, j = 0, bs = 0, js = n; bool k = true;
cout << "输入数量" << endl; cin >> n;
while (j < n)aa[j] = 1 + j++;
j = 0; while (aa[j])cout << aa[j++] << ends; cout << endl;
while (1)
{
bs = j = js = 0;
while (j<n){ if (aa[j])++bs, ++js; if (bs == (k ? 2 : 3)){ aa[j] = 0; bs = 0; --js; }++j; }
if (js <= 3)break;
if (k) k = false; else k = true;
}
j = 0; while (j < n)if (aa[j])cout << aa[j++] << ends; else ++j; cout << endl;
}