通过分支和循环语句了解条件逻辑Learn conditional logic with branch and loop statements

本教程介绍了如何编写代码,从而检查变量,并根据这些变量更改执行路径。This tutorial teaches you how to write code that examines variables and changes the execution path based on those variables. 读者可以编写 C# 代码并查看代码编译和运行结果。You write C# code and see the results of compiling and running it. 本教程包含一系列课程,介绍了 C# 中的分支和循环构造。The tutorial contains a series of lessons that explore branching and looping constructs in C#. 这些课程介绍了 C# 语言的基础知识。These lessons teach you the fundamentals of the C# language.

本教程要求你有一台可用于开发的计算机。This tutorial expects you to have a machine you can use for development. .NET 教程 Hello World 10 分钟入门介绍了如何在 Windows、Linux 或 macOS 上设置本地开发环境。The .NET tutorial Hello World in 10 minutes has instructions for setting up your local development environment on Windows, Linux, or macOS. 熟悉开发工具不仅简要概述了将用到的命令,还收录了详细信息链接。A quick overview of the commands you'll use is in the Become familiar with the development tools with links to more details.

使用 if 语句做出决定Make decisions using the if statement

创建名为 branches-tutorial 的目录。Create a directory named branches-tutorial. 将新建的目录设为当前目录,并运行 dotnet new console -n BranchesAndLoops -o .Make that the current directory and run dotnet new console -n BranchesAndLoops -o .. 此命令会在当前目录中创建一个新的 .NET Core 控制台应用程序。This command creates a new .NET Core console application in the current directory.

在常用编辑器中,打开 Program.cs ,并将行 Console.WriteLine("Hello World!"); 替换为以下代码:Open Program.cs in your favorite editor, and replace the line Console.WriteLine("Hello World!"); with the following code:

int a = 5;
int b = 6;
if (a + b > 10)
    Console.WriteLine("The answer is greater than 10.");

通过在控制台窗口键入 dotnet run 试运行此代码。Try this code by typing dotnet run in your console window. 你应在控制台上看到以下消息:“The answer is greater than 10.You should see the message "The answer is greater than 10." (答案大于 10)”。printed to your console.

修改 b 的声明,让总和小于 10:Modify the declaration of b so that the sum is less than 10:

int b = 3;

再次键入 dotnet runType dotnet run again. 由于答案小于 10,因此什么也没有打印出来。Because the answer is less than 10, nothing is printed. 要测试的条件 为 false。The condition you're testing is false. 没有任何可供执行的代码,因为仅为 if 语句编写了一个可能分支,即 true 分支。You don't have any code to execute because you've only written one of the possible branches for an if statement: the true branch.

提示

在探索 C#(或任何编程语言)的过程中,可能会在编写代码时犯错。As you explore C# (or any programming language), you'll make mistakes when you write code. 编译器会发现并报告这些错误。The compiler will find and report the errors. 仔细查看错误输出和生成错误的代码。Look closely at the error output and the code that generated the error. 编译器错误通常可帮助你找出问题。The compiler error can usually help you find the problem.

第一个示例展示了 if 和布尔类型的用途。This first sample shows the power of if and Boolean types. 布尔 变量可以包含下列两个值之一:truefalseA Boolean is a variable that can have one of two values: true or false. C# 为布尔变量定义了特殊类型 boolC# defines a special type, bool for Boolean variables. if 语句检查 bool 的值。The if statement checks the value of a bool. 如果值为 true,执行 if 后面的语句。When the value is true, the statement following the if executes. 否则,跳过上述语句。Otherwise, it is skipped.

这种检查条件并根据条件执行语句的过程非常强大。This process of checking conditions and executing statements based on those conditions is very powerful.

让 if 和 else 完美配合Make if and else work together

若要执行 true 和 false 分支中的不同代码,请创建在条件为 false 时执行的 else 分支。To execute different code in both the true and false branches, you create an else branch that executes when the condition is false. 试运行这些代码。Try this. 将以下代码中的最后两行添加到 Main 方法(你应该已经有前四个):Add the last two lines in the code below to your Main method (you should already have the first four):

int a = 5;
int b = 3;
if (a + b > 10)
    Console.WriteLine("The answer is greater than 10");
else
    Console.WriteLine("The answer is not greater than 10");

只有当条件的测试结果为 false 时,才执行 else 关键字后面的语句。The statement following the else keyword executes only when the condition being tested is false. ifelse 与布尔条件相结合,可以满足处理 truefalse 所需的一切要求。Combining if and else with Boolean conditions provides all the power you need to handle both a true and a false condition.

重要

ifelse 语句下的缩进是为了方便读者阅读。The indentation under the if and else statements is for human readers. C# 语言忽略缩进或空格。The C# language doesn't treat indentation or white space as significant. ifelse 关键字后面的语句根据条件决定是否执行。The statement following the if or else keyword will be executed based on the condition. 本教程中的所有示例都遵循了常见做法,根据语句的控制流缩进代码行。All the samples in this tutorial follow a common practice to indent lines based on the control flow of statements.

由于缩进会被忽略,因此需要使用 {},指明要在根据条件决定是否执行的代码块中添加多个语句。Because indentation is not significant, you need to use { and } to indicate when you want more than one statement to be part of the block that executes conditionally. C# 程序员通常会对所有 ifelse 子句使用这些大括号。C# programmers typically use those braces on all if and else clauses. 以下示例与刚刚创建的示例相同。The following example is the same as the one you just created. 修改上面的代码以匹配下面的代码:Modify your code above to match the following code:

int a = 5;
int b = 3;
if (a + b > 10)
{
    Console.WriteLine("The answer is greater than 10");
}
else
{
    Console.WriteLine("The answer is not greater than 10");
}

提示

在本教程的其余部分中,代码示例全都遵循公认做法,添加了大括号。Through the rest of this tutorial, the code samples all include the braces, following accepted practices.

可以测试更复杂的条件。You can test more complicated conditions. Main 方法中,在当前已编写的代码之后添加以下代码:Add the following code in your Main method after the code you've written so far:

int c = 4;
if ((a + b + c > 10) && (a == b))
{
    Console.WriteLine("The answer is greater than 10");
    Console.WriteLine("And the first number is equal to the second");
}
else
{
    Console.WriteLine("The answer is not greater than 10");
    Console.WriteLine("Or the first number is not equal to the second");
}

== 符号执行相等 测试。The == symbol tests for equality. 使用 == 将相等测试与赋值测试区分开来,如在 a = 5 中所见。Using == distinguishes the test for equality from assignment, which you saw in a = 5.

&& 表示“且”。The && represents "and". 也就是说,两个条件必须都为 true,才能执行 true 分支中的语句。It means both conditions must be true to execute the statement in the true branch. 这些示例还表明,可以在每个条件分支中添加多个语句,前提是将它们用 {} 括住。These examples also show that you can have multiple statements in each conditional branch, provided you enclose them in { and }.

还可以使用 || 表示“或”。You can also use || to represent "or". 在当前已编写的代码之后添加以下代码:Add the following code after what you've written so far:

if ((a + b + c > 10) || (a == b))
{
    Console.WriteLine("The answer is greater than 10");
    Console.WriteLine("Or the first number is equal to the second");
}
else
{
    Console.WriteLine("The answer is not greater than 10");
    Console.WriteLine("And the first number is not equal to the second");
}

修改 abc 的值,并在 &&|| 之间切换浏览。Modify the values of a, b, and c and switch between && and || to explore. 你将进一步了解 &&|| 运算符的工作原理。You'll gain more understanding of how the && and || operators work.

你已完成第一步。You've finished the first step. 开始进入下一部分前,先将当前代码移到单独的方法中。Before you start the next section, let's move the current code into a separate method. 这样一来,可以更轻松地开始处理新示例。That makes it easier to start working with a new example. Main 方法重命名为 ExploreIf,并编写调用 ExploreIf 的新 Main 方法。Rename your Main method to ExploreIf and write a new Main method that calls ExploreIf. 完成后,代码应如下所示:When you have finished, your code should look like this:

using System;

namespace BranchesAndLoops
{
    class Program
    {
        static void ExploreIf()
        {
            int a = 5;
            int b = 3;
            if (a + b > 10)
            {
                Console.WriteLine("The answer is greater than 10");
            }
            else
            {
                Console.WriteLine("The answer is not greater than 10");
            }

            int c = 4;
            if ((a + b + c > 10) && (a > b))
            {
                Console.WriteLine("The answer is greater than 10");
                Console.WriteLine("And the first number is greater than the second");
            }
            else
            {
                Console.WriteLine("The answer is not greater than 10");
                Console.WriteLine("Or the first number is not greater than the second");
            }

            if ((a + b + c > 10) || (a > b))
            {
                Console.WriteLine("The answer is greater than 10");
                Console.WriteLine("Or the first number is greater than the second");
            }
            else
            {
                Console.WriteLine("The answer is not greater than 10");
                Console.WriteLine("And the first number is not greater than the second");
            }
        }

        static void Main(string[] args)
        {
            ExploreIf();
        }
    }
}

注释掉对 ExploreIf() 的调用。Comment out the call to ExploreIf(). 在本节中,它会在你工作时使输出变得不那么杂乱:It will make the output less cluttered as you work in this section:

//ExploreIf();

// 在 C# 中启动 注释。The // starts a comment in C#. 注释是你想要保留在源代码中但不能作为代码执行的任何文本。Comments are any text you want to keep in your source code but not execute as code. 编译器不会从注释中生成任何可执行代码。The compiler does not generate any executable code from comments.

使用循环重复执行运算Use loops to repeat operations

在本节使用循环 以重复执行语句。In this section you use loops to repeat statements. 请在 Main 方法中试用以下代码:Try this code in your Main method:

int counter = 0;
while (counter < 10)
{
    Console.WriteLine($"Hello World! The counter is {counter}");
    counter++;
}

while 语句会检查条件,并执行 while 后面的语句或语句块。The while statement checks a condition and executes the statement or statement block following the while. 除非条件为 false,否则它会重复检查条件并执行这些语句。It repeatedly checks the condition and executing those statements until the condition is false.

此示例新引入了另外一个运算符。There's one other new operator in this example. counter 变量后面的 ++ 是增量 运算符。The ++ after the counter variable is the increment operator. 它将 counter 值加 1,并将计算后的值存储在 counter 变量中。It adds 1 to the value of counter and stores that value in the counter variable.

重要

请确保 while 循环条件在你执行代码时更改为 false。Make sure that the while loop condition changes to false as you execute the code. 否则,创建的就是无限循环 ,即程序永不结束。Otherwise, you create an infinite loop where your program never ends. 本示例中没有演示上述情况,因为你必须使用 CTRL-C 或其他方法强制退出程序。That is not demonstrated in this sample, because you have to force your program to quit using CTRL-C or other means.

while 循环先测试条件,然后再执行 while 后面的代码。The while loop tests the condition before executing the code following the while. do ... while 循环先执行代码,然后再检查条件。The do ... while loop executes the code first, and then checks the condition. 下面的代码对 Do While 循环进行了演示:The do while loop is shown in the following code:

int counter = 0;
do
{
    Console.WriteLine($"Hello World! The counter is {counter}");
    counter++;
} while (counter < 10);

do 循环和前面的 while 循环生成的输出结果相同。This do loop and the earlier while loop produce the same output.

使用 for 循环Work with the for loop

For 循环通常用在 C# 中。The for loop is commonly used in C#. 请在 Main() 方法中试用以下代码:Try this code in your Main() method:

for (int index = 0; index < 10; index++)
{
    Console.WriteLine($"Hello World! The index is {index}");
}

此循环的工作原理与已用过的 while 循环和 do 循环相同。This does the same work as the while loop and the do loop you've already used. for 语句包含三个控制具体工作方式的部分。The for statement has three parts that control how it works.

第一部分是 for 初始值设定项 :int index = 0; 声明 index 是循环变量,并将它的初始值设置为 0The first part is the for initializer: int index = 0; declares that index is the loop variable, and sets its initial value to 0.

中间部分是 for 条件 :index < 10 声明只要计数器值小于 10,此 for 循环就会继续执行。The middle part is the for condition: index < 10 declares that this for loop continues to execute as long as the value of counter is less than 10.

最后一部分是 for 迭代器 :index++ 指定在执行 for 语句后面的代码块后,如何修改循环变量。The final part is the for iterator: index++ specifies how to modify the loop variable after executing the block following the for statement. 在此示例中,它指定 index 应在代码块每次执行时递增 1。Here, it specifies that index should be incremented by 1 each time the block executes.

亲自试运行这些部分的代码。Experiment with these yourself. 试着执行下列两项操作:Try each of the following:

  • 将初始值设定项更改为其他初始值。Change the initializer to start at a different value.
  • 将结束条件设定项更改为其他值。Change the condition to stop at a different value.

完成后,继续利用所学知识,试着自己编写一些代码。When you're done, let's move on to write some code yourself to use what you've learned.

结合使用分支和循环Combine branches and loops

支持,大家已了解 C# 语言中的 if 语句和循环构造。看看能否编写 C# 代码,计算 1 到 20 中所有可被 3 整除的整数的总和。Now that you've seen the if statement and the looping constructs in the C# language, see if you can write C# code to find the sum of all integers 1 through 20 that are divisible by 3. 下面提供了一些提示:Here are a few hints:

  • % 运算符可用于获取除法运算的余数。The % operator gives you the remainder of a division operation.
  • if 语句中的条件可用于判断是否应将数字计入总和。The if statement gives you the condition to see if a number should be part of the sum.
  • for 循环有助于对 1 到 20 中的所有数字重复执行一系列步骤。The for loop can help you repeat a series of steps for all the numbers 1 through 20.

亲自试一试吧。Try it yourself. 然后,看看自己是怎么做到的。Then check how you did. 你应获取的答案为 63。You should get 63 for an answer. 通过在 GitHub 上查看已完成的代码,你可以看到一个可能的答案。You can see one possible answer by viewing the completed code on GitHub.

已完成“分支和循环”教程。You've completed the "branches and loops" tutorial.

可以在自己的开发环境中继续学习数组和集合教程。You can continue with the Arrays and collections tutorial in your own development environment.

若要详细了解这些概念,请参阅下列主题:You can learn more about these concepts in these topics: