🔄 C++ do...while循环 - L12 进阶概念

掌握do-while循环,至少执行一次的循环结构

📚 什么是do...while循环?

do-while的特点

do-while循环先执行循环体,再判断条件,保证循环体至少执行一次。

  • 至少执行一次
  • ✅ 适合需要先执行后判断的场景
  • ✅ 常用于菜单系统
  • ⚠️ 注意末尾的分号

基本语法

#include <iostream> using namespace std; int main() { int i = 1; // do-while循环:先执行,后判断 do { cout << "第" << i << "次循环" << endl; i++; } while (i <= 5); // 注意这里有分号! cout << "循环结束" << endl; return 0; }
💡 语法要点:
do 后面直接跟代码块
while 在后面,带条件
末尾必须有分号(重要!)
• 先执行一次,再检查条件

⚙️ while vs do-while

关键区别

#include <iostream> using namespace std; int main() { int x = 10; cout << "while循环:" << endl; while (x < 5) { cout << "不会执行" << endl; } cout << "\ndo-while循环:" << endl; do { cout << "至少执行一次" << endl; } while (x < 5); return 0; }
💡 区别总结:
while:先判断,可能一次都不执行
do-while:先执行,至少执行一次
• 当条件初始为假时,差异明显
• do-while适合"至少做一次"的场景
🎮 互动实验:循环对比

观察while和do-while在条件为假时的区别

输入参数后点击"对比"...

🛠️ 常见应用场景

菜单系统(经典应用)

#include <iostream> using namespace std; int main() { int choice; do { cout << "\n=== 菜单 ===" << endl; cout << "1. 功能A" << endl; cout << "2. 功能B" << endl; cout << "0. 退出" << endl; cout << "请选择:"; cin >> choice; switch (choice) { case 1: cout << "执行功能A" << endl; break; case 2: cout << "执行功能B" << endl; break; case 0: cout << "再见!" << endl; break; default: cout << "无效选择" << endl; } } while (choice != 0); return 0; }

输入验证

#include <iostream> using namespace std; int main() { int score; do { cout << "请输入成绩(0-100):"; cin >> score; if (score < 0 || score > 100) { cout << "输入无效,请重新输入!" << endl; } } while (score < 0 || score > 100); cout << "有效成绩:" << score << endl; return 0; }
🎯 菜单模拟器

模拟do-while菜单的执行流程

🚀 三种循环对比

如何选择循环类型

#include <iostream> using namespace std; int main() { cout << "循环选择指南:" << endl; cout << "==================" << endl; cout << "for循环:" << endl; cout << " ✓ 已知循环次数" << endl; cout << " ✓ 遍历数组/序列" << endl; cout << " ✓ 计数循环" << endl; cout << endl; cout << "while循环:" << endl; cout << " ✓ 未知循环次数" << endl; cout << " ✓ 条件驱动" << endl; cout << " ✓ 可能不执行" << endl; cout << endl; cout << "do-while循环:" << endl; cout << " ✓ 至少执行一次" << endl; cout << " ✓ 菜单系统" << endl; cout << " ✓ 输入验证" << endl; return 0; }
💡 选择原则:
• 知道循环次数 → for
• 不知道次数,可能不执行 → while
• 不知道次数,至少执行一次 → do-while
• 三者可以互相转换,选择最清晰的

📝 实战练习

📝 小练习:循环理解

以下代码会输出几次?

#include <iostream> using namespace std; int main() { int i = 10; do { cout << i << " "; i++; } while (i < 5); return 0; }
选择答案查看解析...
💻 编程挑战

题目:使用do-while实现猜数字游戏(输入直到猜对)。

输入数字后点击"生成代码"...