Administrator
发布于 2025-09-21 / 10 阅读
0
0

C#4.3:while循环语句用法详解

1. while循环的基本语法

while (条件表达式)
{
    // 循环体:条件为true时重复执行的代码
}

2. 简单示例入门

示例1:基础计数循环

int count = 1;
while (count <= 5)
{
    Console.WriteLine("这是第 " + count + " 次循环");
    count++; // 重要:必须改变循环条件,否则会无限循环
}

示例2:用户输入验证

string password;
Console.WriteLine("请输入密码:");
password = Console.ReadLine();
​
while (password != "123456") // 当密码不正确时继续循环
{
    Console.WriteLine("密码错误,请重新输入:");
    password = Console.ReadLine();
}
​
Console.WriteLine("登录成功!");

3. while循环的执行流程

开始
↓
检查条件 → false → 结束循环
↓true
执行循环体
↓
返回检查条件

4. 实际应用场景

场景1:菜单系统

bool isRunning = true;
​
while (isRunning)
{
    Console.WriteLine("请选择操作:");
    Console.WriteLine("1. 查看信息");
    Console.WriteLine("2. 修改设置");
    Console.WriteLine("3. 退出");
    
    string choice = Console.ReadLine();
    
    switch (choice)
    {
        case "1":
            Console.WriteLine("显示信息...");
            break;
        case "2":
            Console.WriteLine("修改设置...");
            break;
        case "3":
            isRunning = false; // 改变条件,退出循环
            Console.WriteLine("谢谢使用!");
            break;
        default:
            Console.WriteLine("无效选择,请重新输入");
            break;
    }
}

场景2:数字求和直到0

int sum = 0;
int number;
​
Console.WriteLine("请输入数字(输入0结束):");
number = Convert.ToInt32(Console.ReadLine());
​
while (number != 0)
{
    sum += number; // 累加数字
    Console.WriteLine("当前总和: " + sum);
    Console.WriteLine("请输入下一个数字(输入0结束):");
    number = Convert.ToInt32(Console.ReadLine());
}
​
Console.WriteLine("最终总和: " + sum);

5. 常见错误及避免方法

错误1:无限循环

// 错误示例:缺少改变条件的语句
int x = 1;
while (x <= 5)
{
    Console.WriteLine(x);
    // 忘记写 x++,导致无限循环
}
​
// 正确写法
int x = 1;
while (x <= 5)
{
    Console.WriteLine(x);
    x++; // 确保循环条件会改变
}

错误2:错误的条件判断

// 错误示例:条件永远为true
while (true) // 这会一直循环,除非有break语句
{
    Console.WriteLine("无限循环...");
    // 需要添加退出机制
}
​
// 改进版:添加退出条件
bool running = true;
while (running)
{
    Console.WriteLine("输入 'exit' 退出:");
    string input = Console.ReadLine();
    if (input == "exit")
    {
        running = false;
    }
}

6. while与do-while的区别

// while循环:先判断条件,再执行
int i = 10;
while (i < 5)
{
    Console.WriteLine("这不会执行");
}
​
// do-while循环:先执行一次,再判断条件
int j = 10;
do
{
    Console.WriteLine("这会执行一次"); // 尽管条件不满足,但仍会执行一次
    j++;
} while (j < 5);

7. 综合练习项目

练习:猜数字游戏

Random random = new Random();
int secretNumber = random.Next(1, 101); // 1-100的随机数
int guess = 0;
int attempts = 0;
​
Console.WriteLine("猜数字游戏开始! (1-100)");
​
while (guess != secretNumber)
{
    Console.Write("请输入你的猜测: ");
    guess = Convert.ToInt32(Console.ReadLine());
    attempts++;
    
    if (guess < secretNumber)
    {
        Console.WriteLine("猜小了!");
    }
    else if (guess > secretNumber)
    {
        Console.WriteLine("猜大了!");
    }
    else
    {
        Console.WriteLine($"恭喜! 你在{attempts}次尝试后猜对了!");
    }
}

8. 调试技巧

  1. 使用断点:在循环开始处设置断点,观察变量变化

  2. 添加调试输出

    while (condition)
    {
        Console.WriteLine($"调试: 变量值 = {variable}"); // 跟踪变量变化
        // 循环代码
    }

总结

  • while循环在不确定需要循环多少次的情况下非常有用

  • 确保循环条件最终会变为false,避免无限循环

  • 使用计数器标志变量控制循环执行

  • 多练习实际场景中的应用,如菜单系统、输入验证等

练习

给你的挑战:尝试编写一个程序,使用while循环计算用户输入的一系列数字的平均值,当用户输入"done"时结束输入并显示结果。

记住,掌握循环的关键是多实践。尝试修改上面的示例,创造你自己的循环程序!


评论