FreeBasic Do Loop 关键字
最后修改日期:2025 年 6 月 16 日
FreeBasic 的 Do
和 Loop
关键字用于创建重复代码块的循环。它们提供了具有不同条件检查位置的灵活控制结构。
基本定义
在 FreeBasic 中,Do
和 Loop
结合使用来创建循环结构。循环将持续进行,直到满足指定条件为止。
有四种主要变体:Do While
、Do Until
、Loop While
和 Loop Until
。每种变体在循环执行的不同位置检查条件。
基本 Do Loop
此示例展示了使用 Do/Loop 的最简单的无限循环结构。
Dim counter As Integer = 0 Do counter += 1 Print "Counter: "; counter If counter >= 5 Then Exit Do End If Loop Print "Loop ended"
这创建了一个无限循环,该循环会递增一个计数器。当计数器达到 5 时,Exit Do
语句会中断循环。如果没有 Exit Do,此循环将无限运行。
Do While Loop
Do While
循环在每次迭代之前检查条件。
Dim number As Integer = 1 Do While number <= 10 Print "Number: "; number number += 2 Loop Print "Loop completed"
此循环打印 1 到 10 之间的奇数。条件在每次迭代之前都会被检查。如果初始条件为假,则循环体永远不会执行。变量在循环内部修改,以最终使条件变为假。
Do Until Loop
Do Until
循环会一直运行,直到条件变为真。
Dim password As String Dim attempts As Integer = 0 Do Until password = "secret" Or attempts >= 3 Input "Enter password: ", password attempts += 1 Loop If password = "secret" Then Print "Access granted" Else Print "Too many attempts" End If
此循环会提示输入密码,直到输入正确密码或进行 3 次尝试。与 While 不同,Until 会持续运行直到条件变为真,而不是在条件保持为真时持续运行。
Loop While
Loop While
在每次迭代之后检查条件。
Dim response As String Do Input "Do you want to continue (yes/no)? ", response response = LCase(response) Loop While response = "yes" Print "Goodbye"
此循环在检查条件之前至少执行一次。它会在用户输入“yes”时继续。条件在循环体完成每次迭代后进行评估。
Loop Until
Loop Until
在每次迭代之后检查其条件。
Dim randomNum As Integer Dim guess As Integer Dim tries As Integer = 0 Randomize Timer randomNum = Int(Rnd * 10) + 1 Do Input "Guess the number (1-10): ", guess tries += 1 If guess < randomNum Then Print "Too low" ElseIf guess > randomNum Then Print "Too high" End If Loop Until guess = randomNum Print "Correct! You guessed it in "; tries; " tries"
这个数字猜谜游戏循环会一直运行,直到猜对数字为止。每次尝试后都会检查条件。循环在检查退出条件之前总是至少运行一次。
嵌套的 Do Loops
Do 循环可以嵌套在其他 Do 循环中,以实现复杂的逻辑。
Dim i As Integer = 1 Do While i <= 3 Dim j As Integer = 1 Do While j <= 3 Print "i:"; i; " j:"; j j += 1 Loop i += 1 Loop Print "Nested loops completed"
此示例展示了两个嵌套的 Do While 循环。外层循环运行 3 次,对于外层循环的每次迭代,内层循环运行 3 次。这使得内层循环体总共执行 9 次(3×3)。
带 Continue 的 Do Loop
Continue Do
语句会跳过当前迭代的其余部分。
Dim n As Integer = 0 Do While n < 10 n += 1 If n Mod 2 = 0 Then Continue Do End If Print "Odd number: "; n Loop Print "Finished"
此循环打印 1 到 10 之间的奇数。当遇到偶数时,Continue Do
会跳过打印语句并跳转到下一次迭代。循环条件仍会正常检查。
最佳实践
- 初始化:始终在循环开始前初始化循环控制变量。
- 终止:确保循环有一个清晰的退出条件。
- 可读性:在可能的情况下,优先使用 While/Until 条件而不是 Exit Do。
- 性能:将不变量计算移到循环外部。
- 缩进:为使循环体清晰,请始终保持一致的缩进。
本教程介绍了 FreeBasic 的 Do
和 Loop
关键字,并提供了实用的示例来展示不同的循环结构。