跳转到内容

C Sharp While 循环

来自代码酷

C# While循环[编辑 | 编辑源代码]

While循环是C#中最基础的控制流结构之一,它允许代码在满足特定条件时重复执行一段语句。与for循环不同,while循环更适用于不确定循环次数的场景。

基本语法[编辑 | 编辑源代码]

C#中的while循环语法如下:

while (condition)
{
    // 循环体代码
}

其中:

  • condition是一个布尔表达式(返回true或false)
  • 循环会持续执行,直到condition变为false
  • 循环体可以是单条语句或代码块(用花括号包裹)

工作原理[编辑 | 编辑源代码]

flowchart TD A[开始] --> B{条件为真?} B -- 是 --> C[执行循环体] C --> B B -- 否 --> D[结束循环]

数学上可以表示为:当P(n)为真时,重复执行语句Swhile P(n) do S

基础示例[编辑 | 编辑源代码]

简单计数器[编辑 | 编辑源代码]

int count = 0;
while (count < 5)
{
    Console.WriteLine($"当前计数: {count}");
    count++;
}

输出

当前计数: 0
当前计数: 1
当前计数: 2
当前计数: 3
当前计数: 4

用户输入验证[编辑 | 编辑源代码]

string userInput;
while (true)
{
    Console.Write("请输入'quit'退出: ");
    userInput = Console.ReadLine();
    if (userInput == "quit")
        break;
    Console.WriteLine($"你输入了: {userInput}");
}

输出(示例交互):

请输入'quit'退出: hello
你输入了: hello
请输入'quit'退出: test
你输入了: test
请输入'quit'退出: quit

高级用法[编辑 | 编辑源代码]

嵌套while循环[编辑 | 编辑源代码]

int i = 1;
while (i <= 3)
{
    int j = 1;
    while (j <= 3)
    {
        Console.WriteLine($"i={i}, j={j}");
        j++;
    }
    i++;
}

输出

i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=2, j=2
i=2, j=3
i=3, j=1
i=3, j=2
i=3, j=3

复杂条件[编辑 | 编辑源代码]

Random random = new Random();
int target = random.Next(1, 101);
int guess;
int attempts = 0;

Console.WriteLine("猜数字游戏(1-100)");
while ((guess = Convert.ToInt32(Console.ReadLine())) != target)
{
    attempts++;
    Console.WriteLine(guess < target ? "太小了" : "太大了");
}
Console.WriteLine($"恭喜!你用了{attempts}次猜中了数字{target}");

常见错误与陷阱[编辑 | 编辑源代码]

1. 无限循环:忘记更新循环变量

// 错误示例
int x = 0;
while (x < 10)
{
    Console.WriteLine(x);
    // 缺少x++会导致无限循环
}

2. 错误的条件表达式:可能导致循环一次都不执行

int y = 10;
while (y < 5)  // 条件初始就不成立
{
    Console.WriteLine(y);
    y++;
}

3. 使用浮点数作为循环条件:由于浮点精度问题可能导致意外行为

double d = 0.1;
while (d != 1.0)  // 不推荐这样比较浮点数
{
    d += 0.1;
}

实际应用案例[编辑 | 编辑源代码]

文件读取[编辑 | 编辑源代码]

using System.IO;

StreamReader file = new StreamReader("data.txt");
string line;
while ((line = file.ReadLine()) != null)
{
    Console.WriteLine(line);
}
file.Close();

游戏主循环[编辑 | 编辑源代码]

bool gameRunning = true;
while (gameRunning)
{
    ProcessInput();
    UpdateGameState();
    RenderGraphics();
    
    gameRunning = !CheckExitCondition();
}

性能考虑[编辑 | 编辑源代码]

  • while循环的性能与for循环相当
  • 避免在循环条件中进行复杂计算:
// 不佳实践
while (ComplexCalculation() > threshold)
{
    // ...
}

// 更好做法
double result = ComplexCalculation();
while (result > threshold)
{
    // ...
    result = ComplexCalculation();
}

与do-while的区别[编辑 | 编辑源代码]

  • while循环先检查条件后执行
  • do-while循环至少执行一次,再检查条件
  • 选择依据取决于是否需要至少执行一次循环体

最佳实践[编辑 | 编辑源代码]

1. 确保循环变量最终会使条件变为false 2. 复杂的条件可以考虑提取为方法或变量 3. 对于集合遍历,通常foreach更合适 4. 考虑使用break和continue语句控制流程 5. 保持循环体简洁,复杂逻辑提取为方法

练习建议[编辑 | 编辑源代码]

1. 实现一个倒计时程序 2. 编写程序计算数字的阶乘 3. 创建简单的菜单系统 4. 模拟银行账户的密码输入尝试限制