Microsoft 2023 年所提供的 C# codecamp 基礎課程,總共有 38 個單元,完成後就可以獲得 Certification ,今天要來跟大家分享的是第九單元章節的內容。
本節內容
if 陳述式
if 陳述式依賴用一組括弧括住的布林運算式。 如果運算式為 True,則會執行陳述式 if 之後的程式碼。 如果不是,NET 執行階段會忽略該程式碼,而且不會執行。
布林運算式
布林運算式是任何會傳回布林值 (true 或 false) 的程式碼。 最簡單的布林運算式就只是值 true 與 false。 或者,布林運算式可以是傳回值 true 或 false 的方法結果。 
該運算式可以使用其他的運算子來比較計算的值,其中包括:
- ==,用來測試是否相等的「等於」運算子
- >,用來測試左邊值是否大於右邊值的「大於」運算子
- <,用來測試左邊值是否小於右邊值的「小於」運算子
- >=,「大於或等於」運算子
- <=,「小於或等於」運算子
擲骰題目練習
  | 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 
 | Random dice = new Random();
 int roll1 = dice.Next(1, 7);
 int roll2 = dice.Next(1, 7);
 int roll3 = dice.Next(1, 7);
 
 int total = roll1 + roll2 + roll3;
 
 Console.WriteLine($"Dice roll: {roll1} + {roll2} + {roll3} = {total}");
 
 if ((roll1 == roll2) || (roll2 == roll3) || (roll1 == roll3))
 {
 if ((roll1 == roll2) && (roll2 == roll3))
 {
 Console.WriteLine("You rolled triples!  +6 bonus to total!");
 total += 6;
 }
 else
 {
 Console.WriteLine("You rolled doubles!  +2 bonus to total!");
 total += 2;
 }
 }
 
 if (total >= 16)
 {
 Console.WriteLine("You win a new car!");
 }
 else if (total >= 10)
 {
 Console.WriteLine("You win a new laptop!");
 }
 else if (total == 7)
 {
 Console.WriteLine("You win a trip for two!");
 }
 else
 {
 Console.WriteLine("You win a kitten!");
 }
 
 | 
訂閱制範例練習
  | 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 
 | Random random = new Random();int daysUntilExpiration = random.Next(12);
 int discountPercentage = 0;
 
 if( daysUntilExpiration <=10 )
 {
 if ( daysUntilExpiration == 0){
 Console.WriteLine("Your subscription has expired.");
 }
 else if ( daysUntilExpiration <= 1 ){
 Console.WriteLine("Your subscription expires within a day!");
 discountPercentage = 20;
 }
 else if (daysUntilExpiration <= 5 ){
 Console.WriteLine($"Your subscription expires in {daysUntilExpiration} days.");
 discountPercentage = 10;
 }
 };
 
 if(discountPercentage > 0)
 {
 Console.WriteLine($"Renew now and save {discountPercentage}%.");
 };
 
 | 
重點整理
透過大量的範例讓大家練習 if… else 的判斷,官方的寫法比較簡單暴力一點,我最後選擇使用自己的寫法記錄在這邊。
感覺好像什麼大考前的複習,一直在看很多基礎的東西哈哈。
那我們下次見ʘ‿ʘ
參考資料