while循环语句

while循环是C#中最基本的循环结构之一,用于在条件为真时重复执行代码块。本教程将详细介绍while循环的语法、使用方法和常见应用场景。

1. 概述

while循环是一种前测试循环结构,即在执行循环体之前先检查条件。如果条件为true,则执行循环体;如果条件为false,则跳过循环。while循环适用于不确定循环次数的情况。

2. 基本语法

while循环的基本语法如下:

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

其中:

  • 条件表达式:必须是一个布尔表达式,每次循环开始前都会检查
  • 循环体:当条件为true时执行的代码块

3. 基本用法示例

示例:输出1到10的数字

int i = 1;

while (i <= 10)
{
    Console.WriteLine(i);
    i++; // 重要:更新循环变量,避免无限循环
}

输出结果:

1
2
3
4
5
6
7
8
9
10

4. while循环的执行流程

执行步骤

  1. 检查条件表达式是否为true
  2. 如果为true,执行循环体中的代码
  3. 执行完循环体后,回到步骤1
  4. 如果为false,跳出循环,继续执行后面的代码

5. 常见应用场景

场景1:读取用户输入直到满足条件

string input;

Console.WriteLine("请输入'exit'退出程序:");

while ((input = Console.ReadLine()) != "exit")
{
    Console.WriteLine("您输入了:" + input);
    Console.WriteLine("请输入'exit'退出程序:");
}

Console.WriteLine("程序已退出");

场景2:计算累加和

int sum = 0;
int number = 1;

while (number <= 100)
{
    sum += number;
    number++;
}

Console.WriteLine("1到100的和是:" + sum);

场景3:查找数组中的元素

int[] numbers = { 5, 12, 8, 3, 15, 7 };
int target = 8;
int index = 0;
bool found = false;

while (index < numbers.Length && !found)
{
    if (numbers[index] == target)
    {
        found = true;
    }
    else
    {
        index++;
    }
}

if (found)
{
    Console.WriteLine($"找到{target},位置在索引{index}");
}
else
{
    Console.WriteLine("未找到" + target);
}

6. 无限循环

如果条件永远为true,while循环会变成无限循环。在某些情况下,这可能是需要的,但通常是由于错误导致的。

示例:有意创建的无限循环

while (true)
{
    Console.WriteLine("这是一个无限循环");
    Console.WriteLine("按Ctrl+C退出");
    
    // 添加适当的退出条件
    if (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape)
    {
        break;
    }
}

7. 注意事项

重要注意事项

  • 确保循环条件最终会变为false:否则会导致无限循环
  • 在循环体内更新循环变量:确保每次循环都有进展
  • 注意循环边界条件:避免数组越界等错误
  • 考虑使用break语句:在满足特定条件时提前退出循环
  • 考虑使用continue语句:跳过本次循环的剩余部分

8. break和continue语句

在while循环中,可以使用break和continue语句来控制循环流程。

示例:使用break和continue

int i = 1;

while (i <= 10)
{
    if (i == 5)
    {
        i++;
        continue; // 跳过本次循环
    }
    
    if (i == 8)
    {
        break; // 退出整个循环
    }
    
    Console.WriteLine(i);
    i++;
}

输出结果:

1
2
3
4
6
7

9. 嵌套while循环

while循环可以嵌套使用,形成多层循环结构。

示例:打印乘法表

int i = 1;

while (i <= 9)
{
    int j = 1;
    while (j <= i)
    {
        Console.Write($"{j}×{i}={i*j} ");
        j++;
    }
    Console.WriteLine();
    i++;
}

10. 常见错误与解决方案

错误1:忘记更新循环变量

// 错误示例
int i = 1;
while (i <= 10)
{
    Console.WriteLine(i);
    // 忘记了 i++;
}
// 正确示例
int i = 1;
while (i <= 10)
{
    Console.WriteLine(i);
    i++; // 更新循环变量
}

错误2:循环条件错误

// 错误示例
int i = 1;
while (i < 10) // 应该是 <= 10
{
    Console.WriteLine(i);
    i++;
}
// 正确示例
int i = 1;
while (i <= 10)
{
    Console.WriteLine(i);
    i++;
}

错误3:数组越界

// 错误示例
int[] arr = { 1, 2, 3 };
int i = 0;
while (i <= arr.Length) // 应该是 < arr.Length
{
    Console.WriteLine(arr[i]);
    i++;
}
// 正确示例
int[] arr = { 1, 2, 3 };
int i = 0;
while (i < arr.Length)
{
    Console.WriteLine(arr[i]);
    i++;
}

11. 完整示例程序

示例:猜数字游戏

using System;

class Program
{
    static void Main(string[] args)
    {
        Random random = new Random();
        int targetNumber = random.Next(1, 101);
        int attempts = 0;
        bool guessed = false;

        Console.WriteLine("=== 猜数字游戏 ===");
        Console.WriteLine("我已经想好了一个1到100之间的数字,请你来猜!");

        while (!guessed)
        {
            attempts++;
            Console.Write($"第{attempts}次尝试,请输入你的猜测:");
            
            if (int.TryParse(Console.ReadLine(), out int guess))
            {
                if (guess < targetNumber)
                {
                    Console.WriteLine("太小了!再大一点。");
                }
                else if (guess > targetNumber)
                {
                    Console.WriteLine("太大了!再小一点。");
                }
                else
                {
                    Console.WriteLine($"恭喜你猜对了!数字是{targetNumber}");
                    Console.WriteLine($"你总共用了{attempts}次尝试。");
                    guessed = true;
                }
            }
            else
            {
                Console.WriteLine("请输入有效的数字!");
            }
        }

        Console.WriteLine("游戏结束,按任意键退出...");
        Console.ReadKey();
    }
}

12. 总结

while循环是C#中最基本的循环结构之一,它具有以下特点:

  • 前测试循环:先检查条件,再执行循环体
  • 适用场景:不确定循环次数的情况
  • 灵活性:可以配合break、continue等语句使用
  • 注意事项:确保循环条件最终会变为false

通过本教程的学习,你应该掌握了:

  • while循环的基本语法和使用方法
  • while循环的执行流程
  • break和continue语句的使用
  • 嵌套while循环的使用
  • 常见错误与解决方案

熟练掌握while循环是学习C#编程的基础,它将帮助你编写更加灵活和强大的程序。