循环逻辑-while

语法规则

  • while循环的语法规则:先执行while中的循环条件判断。如果是true,就执行一遍循环体。如果是false,就不执行循环体了。
  • 执行完循环体后,会再次判断while中的循环条件判断。
  • 如果第一次循环条件判断就为false,那循环体就一次也不会执行。
    while(循环条件判断)
    {
        // 循环体
    }
    

应用案例

  • 死循环。如果while中的逻辑运算永远为true,将会出现无法退出的循环。

    while(true)
    {
        Console.WriteLine("这是一个死循环");
    }
    
  • 打印3遍

    int i = 0;
    while (i < 3)
    {
        Console.WriteLine("重要的事说三遍。");
        i++;
    }
    
  • 打印0~100

    int i = 0;
    while (i <= 100)
    {
        Console.WriteLine(i);
        i++;
    }
    

使用场景

从编程思想的角度讲以下3种情况可以使用while循环。

  • 死循环。
  • 只要...就... 。只要条件满足就执行循环体。

    // 猜商品的价格
    Random r = new Random();
    int cost = r.Next(100, 1000); // 商品的价格在100~1000之间
    int guess = -1; // guess用来存用户猜的价格
    
    // 只要没猜对,就接着猜。
    while (guess != cost)
    {
        guess = Int32.Parse(Console.ReadLine());
        if (guess > cost) 
        {
          Console.WriteLine("大了");
        }
        else if (guess <cost)
        {
          Console.WriteLine("小了");
        }
    }
    
    Console.WriteLine("猜对了");
    
  • 直到...才...。

    // 猜商品的价格
    Random r = new Random();
    int cost = r.Next(100, 1000); // 商品的价格在100~1000之间
    int guess = -1; // guess用来存用户猜的价格
    
    // 直到猜对才结束。使用死循环。
    while (true)
    {
      guess = Int32.Parse(Console.ReadLine());
    
      // 直到猜对了才退出
      if (guess == cost)
        break; // 循环的退出参见后续章节
    
      if (guess > cost) 
      {
        Console.WriteLine("大了");
      }
      else if( guess < cost)
      {
        Console.WriteLine("小了");
      }
    }
    
    Console.WriteLine("猜对了");
    

results matching ""

    No results matching ""