C# 流程控制

在前幾篇有介紹了邏輯運算子,其主要會與 if 做搭配,而本篇要認識如何運用流程控制

而流程控制的條件選擇中,主要有 :

單向選擇

  if (條件運算式)

  {

       敘述..;

  }

{
  if (score < 60)
  {
     Console.WriteLine("不及格");
  }
}

也可寫成

{
   if (score < 60) Console.WriteLine("不及格");
}
{
   if (score < 60)
     Console.WriteLine("不及格");
}

 

雙向選擇

  if (條件運算式)

  {

       敘述 A..;

  }

  else

  {

     敘述 B..;

  }

{
   if (score > 60)
   {
      Console.WriteLine("及格");
   }
   else
   {
      Console.WriteLine("不及格");
   }
}

也可以加入更多條件

{
   if (score >= 20 && score < 25)
   {
      Console.WriteLine("您的BMI指數:正常");
   }
   else if (score >= 25 && score < 28)
   {
      Console.WriteLine("您的BMI指數:體重過重");
   }
   else if (score >= 28)
   {
      Console.WriteLine("您的BMI指數:肥胖");
   }
}

 

多向選擇

三元運算子

變數 = 運算式 ? 變數1 : 變數2 ;
int a= b > 1 ? b : c ;

宣告變數a,並判斷如果b的值>1,就將b值給a,否則則將c值給a。

使用三元運算子,也可以簡化程式碼

 

巢狀結構

{
   int temperature = int.Parse(Console.ReadLine()); // 室外溫度
   int humidity = int.Parse(Console.ReadLine()); // 室外濕度

   if (temperature >= 30)
   {
      if (humidity >= 70 && humidity < 90)
      {
         Console.WriteLine(今天非常濕熱);
      }
      else if (humidity >= 60 && humidity < 70)
      {
         Console.WriteLine(今天天氣炎熱);
      }
   }
   if (temperature < 30)
   {
      if (humidity >= 60 && humidity < 70)
      {
         Console.WriteLine(今天天氣適中);
      }
      else if (humidity >= 30 && humidity < 60)
      {
         Console.WriteLine(今天天氣涼爽);
      }
   }
}

 

switch

如果是多個不同條件選擇時,就需使用多層次的 if,但當只有一個條件而有多種選擇時,則可以使用switch

switch運算式可以是數值、字串

測試值與運算式值的資料型別需相同

switch (運算式)

{

   case 1 測試值: 

         ......

        break ;

   case 2 測試值: 

         ......

        break ;

   default :

        ......

        break ;

}

{
   Console.WriteLine("請輸入今日天氣");

   string name = Console.ReadLine();

   switch (name)
   {
      case "晴天":
         Console.WriteLine("適合出門");
         break; //跳離當前函數,跳離當前的位置(離開)
      case "雨天":
         Console.WriteLine("不適合出門");
         break;
      case "陰天":
         Console.WriteLine("出門請多留意天氣狀況");
         break;
      default:
         Console.WriteLine("您輸入不明確,但出門請多留意天氣狀況");
         break;

    }
}
{
    int num = 1;
      
    switch (num)
    {
        case 1:
          Console.WriteLine("Case 1");
          break;
        case 2:
          Console.WriteLine("Case 2");
          break;
        default:
          Console.WriteLine("Default case");
          break;
     }
}

 

 

 

新人發文,文章敘述如有錯誤及觀念不正確,請不吝嗇指教,感謝~

參考文件 https://docs.microsoft.com/zh-tw/dotnet/csharp/language-reference/operators/conditional-operator

參考文件 https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/switch