C++ 基础 3 第 67-69 关
LOOPING
🎛️

循环控制:Continue & Break

Loop Control Statements

⏭️ Continue (跳过)
🛑 Break (停止)
⏭️

Continue:跳过本轮

continue 就像循环的“跳过按钮”。

当遇到它时,循环会立即放弃当前这轮剩下的工作,直接开始下一轮。

if (apple.isBad) { continue; // 坏苹果?不要了,下一个! } pack(apple); // 只有好苹果才会执行到这
"就像检查苹果,看到坏的直接扔掉,看下一个!"
🚮
📦
🧪

实战 I:炼金术传承

我们要避开毒药,只拿好的药水。

while(true) { auto item = hero.findNearestItem(); // 1. 没东西?跳过 if (!item) { continue; } // 2. 是毒药?跳过 if (item.type == "poison") { continue; } // 3. 安全!去拿 hero.moveXY(item.pos.x, item.pos.y); }
找到物品
⬇️
是毒药吗?
↙️ 是 (continue)
否 ↘️
去收集
⤴️ 回到开头
🌵

实战 II:伪装大师

如果看见敌人,就装成仙人掌不动(跳过移动代码)。

while(true) { auto enemy = hero.findNearestEnemy(); // 如果有敌人,不要动!直接跳到下一轮循环 if (enemy) { continue; } // 如果没有敌人,才去拿宝石 auto item = hero.findNearestItem(); if (item) { hero.moveXY(item.pos.x, item.pos.y); } }
💂‍♂️ 👀
🌵
Continue!
🛑

Break:循环出口

break 就像循环的“紧急出口”。

当遇到它时,循环会彻底停止,不再继续执行。

while (true) { count += 1; if (count > 20) { break; // 够了!停! } }
"就像数糖果,数满20颗就收工回家!"
0
Limit: 10
BREAK!
🏃

终极挑战:逃到春天

我们需要结合 breakcontinue 来完成复杂任务。

  1. 前30秒,打怪(忽略特定的怪)。
  2. 然后,去收集金币,直到够20金。
  3. 最后,逃跑!
// 第一阶段:战斗 while (true) { if (hero.time > 30) break; // 时间到,退出战斗循环 auto enemy = hero.findNearestEnemy(); if (enemy) { // 如果是巨人或耗牛,跳过 if (enemy.type == "burl" || enemy.type == "sand-yak") { continue; } hero.attack(enemy); } }
🚪
🎓

控制大师口诀

"continue 是跳过,
坏的不要,看下一个!"
"break 是出口,
任务完成,立马就走!"
🚦