手把手教编写程序-士兵队列训练问题

作者在 2020-02-06 04:01:46 发布以下内容
1审阅题目后决定采用固定数组来处理,动态数组在之后自己去实现
2看2个示例先写一个100的数组并赋值为输入的数量,同时进行初始化后输出,观察程序是否按意图正常运行:
int aa[100]{0},n=0,j=0;
cout << "输入数量" << endl;cin>>n;
while(j<n)aa[j]=1+j++;
j=0;while(aa[j])cout<<aa[j++]<<ends;cout<<endl;
3依据题目条件先写一个报数2剔除的,把凡是报2的数组赋值为0即可
int bs=0;j=0;
while(j<n){if(aa[j])++bs;if(bs==2){aa[j]=0;bs=0;}++j;}
4剔除报2的数组后输出看看
j=0;while(j<n)if(aa[j])cout<<aa[j++]<<ends;else ++j;cout<<endl;
5接着按上面的写报3的剔除
看看报2剔除的输出

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;
}
观察输出是否正确运行

逃跑的蠕虫.png (上传于2020-02-06 04:02:44)
逃跑的蠕虫.png

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++] = j + 1;
 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;

默认分类 | 阅读 2499 次
文章评论,共5条
零度酷冷
2020-03-04 15:15
1
大佬能教我入门吗??一点也不会
xianfajushi(作者)
2020-03-14 07:44
2
有问题可提出来。
升何泵独(游客)
2020-03-24 23:03
3
and me!
零度酷冷
2020-04-08 16:35
4
以下是引用xianfajushi在2020-03-14 07:44的发言1
有问题可提出来。
不是问题是我完全不知道学那个
xianfajushi(作者)
2020-04-08 19:49
5
学的是编程的思想和逻辑,非具体语言,这样的观点就能进入编程三昧。 
游客请输入验证码