核心任务:
1. 找出特殊的那个 (Min/Max)
2. 跳着数数 (Step)
沙漠里全是硬币,眼镜坏了 (findNearest 不可用),我要自己写代码找到离我最近的那一枚!
auto nearest = null; float minDist = 9999; // 初始设个超级大的数 int index = 0; while (index < coins.size()) { auto coin = coins[index]; float dist = hero.distanceTo(coin); // 👇 挑战擂主!如果现在的更近 if (dist < minDist) { nearest = coin; // 更新最近的硬币 minDist = dist; // 更新最短距离记录 } index++; }
auto farthest = null; float maxDist = 0; // 初始设为 0 (最小) int index = 0; while (index < enemies.size()) { auto enemy = enemies[index]; float dist = hero.distanceTo(enemy); // 👇 挑战擂主!如果现在的更远 if (dist > maxDist) { maxDist = dist; // 更新最长距离 farthest = enemy; // 更新最远的敌人 } index++; }
和找最小值完全相反:
我们要处理一个混合名单:兽人 和 朋友 混在一起。
是兽人 (Enemy) → 攻击!
是朋友 (Friend) → 跳过!
平时我们是一个一个数:index++ (即 index += 1)
这次我们要跳着数:index += 2
auto everybody = {"Yetu", "Tabitha", "Rasha"...}; int index = 0; while (index < everybody.size()) { auto enemy = everybody[index]; // ⚔️ 攻击兽人 hero.attack(enemy); // 🏃♂️ 关键:每次加 2,跳过朋友! index += 2; }
这些代码以后会经常用到,请记在小本本上!
每一个都看
index++
隔一个看一个
index += 2
打擂台法
if (score > best)