D編程 switch statement

2021-09-01 11:24 更新

switch語句允許根據(jù)值判斷是否相等性,每個(gè)值稱為一個(gè)case語句,并且為每個(gè)switch case檢查每個(gè)變量。

switch - 語法

D編程語言中switch語句語法如下所示:-

switch(expression) { 
   case constant-expression  : 
      statement(s); 
      break; /* optional */

   case constant-expression  : 
      statement(s); 
      break; /* optional */
      * you can have any number of case statements */

   default : /* Optional */
      statement(s); 
}

switch - 流程圖

switch statement in D

switch - 示例

import std.stdio;
 
int main () { 
   /* local variable definition */
   char grade='B';
   switch(grade) { 
      case 'A' : 
         writefln("Excellent!" ); 
         break; 
      case 'B' : 
      case 'C' : 
         writefln("Well done" ); 
         break; 
      case 'D' : 
         writefln("You passed" ); 
         break; 
      case 'F' : 
         writefln("Better try again" ); 
         break; 
      default : 
         writefln("Invalid grade" ); 
   } 
   writefln("Your grade is %c", grade ); 
  
   return 0; 
} 

編譯并執(zhí)行上述代碼時(shí),將生成以下結(jié)果-

Well done 
Your grade is B


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)