如何使用 C# do while 循环?

csharpprogrammingserver side programming更新于 2025/7/13 3:22:17

do...while 循环在循环结束时检查其条件。它与 while 循环类似,但 do...while 循环保证至少执行一次。

创建 do while 循环 −

do {
   statement(s);
} while( condition );

条件表达式出现在循环末尾,因此循环中的语句在条件测试之前会执行一次。

如果条件为真,控制流将跳转回 do 循环,并再次执行循环中的语句。重复此过程,直到给定条件变为假。

下面是三个 −

示例

using System;

namespace Loops {
   class Program {
      static void Main(string[] args) {
          /* 局部变量定义 */
         int a = 50;

          /* 执行循环 */
         do {
            Console.WriteLine("value of a: {0}", a);
            a = a + 1;
         }

         while (a < 20);
         Console.ReadLine();
      }
   }
}

输出

value of a: 50

相关文章