5. 实际应用场景
场景1:密码验证(确保至少询问一次)
string password;
do
{
Console.WriteLine("请输入密码:");
password = Console.ReadLine();
if (password != "123456")
{
Console.WriteLine("密码错误!");
}
} while (password != "123456");
Console.WriteLine("登录成功!");
场景2:数字求和(至少处理一个数字)
int sum = 0;
int number;
char continueInput;
do
{
Console.WriteLine("请输入一个数字:");
number = Convert.ToInt32(Console.ReadLine());
sum += number;
Console.WriteLine("当前总和: " + sum);
Console.WriteLine("是否继续输入? (y/n)");
continueInput = Console.ReadKey().KeyChar;
Console.WriteLine(); // 换行
} while (continueInput == 'y' || continueInput == 'Y');
Console.WriteLine("最终总和: " + sum);
场景3:游戏中的主循环
bool playAgain;
int score;
do
{
// 游戏逻辑
Console.WriteLine("游戏开始...");
score = new Random().Next(50, 100);
Console.WriteLine("你的得分: " + score);
// 询问是否再玩一次
Console.WriteLine("是否再玩一次? (y/n)");
char response = Console.ReadKey().KeyChar;
playAgain = (response == 'y' || response == 'Y');
Console.WriteLine(); // 换行
} while (playAgain);
Console.WriteLine("谢谢游玩!");
8. 综合练习项目
练习:简单的计算器
char operation;
double result = 0;
do
{
Console.WriteLine("当前结果: " + result);
Console.WriteLine("请选择操作: (+, -, *, /, c=清除, e=退出)");
operation = Console.ReadKey().KeyChar;
Console.WriteLine(); // 换行
if (operation == 'e' || operation == 'E') break;
if (operation == 'c' || operation == 'C')
{
result = 0;
continue;
}
Console.WriteLine("请输入数字:");
double number = Convert.ToDouble(Console.ReadLine());
switch (operation)
{
case '+':
result += number;
break;
case '-':
result -= number;
break;
case '*':
result *= number;
break;
case '/':
if (number != 0)
result /= number;
else
Console.WriteLine("错误: 除数不能为零!");
break;
default:
Console.WriteLine("无效操作!");
break;
}
} while (true);
Console.WriteLine("计算器已关闭");
9. 调试技巧
在循环开始处设置断点,观察第一次执行的情况
添加调试输出,跟踪变量变化:
do { Console.WriteLine($"调试: 变量值 = {variable}"); // 循环代码 } while (condition);
总结
do-while循环至少执行一次循环体,然后检查条件
语法上必须以分号
;
结束最适合需要至少执行一次的场景,如菜单、用户输入验证等
避免无限循环,确保循环条件最终会变为false
练习
实践挑战:创建一个问答游戏,使用do-while循环让用户回答多个问题,最后显示得分。用户可以选择是否再玩一次。
记住关键原则:当你需要确保代码块至少执行一次时,使用do-while循环。多练习不同场景,你会很快掌握它的用法!