C# 新手入門(4) 布林運算,if,Switch,Array陣列,List,迴圈

來自 | 7 月 12, 2024 | 程式 | 0 條留言

此篇會把常用的控制程式執行順序教完,預計有

  1. if ..else 判斷
  2. inline if ,行內if
  3. switch case 也是判斷
  4. array 陣列
  5. List 也是陣列
  6. for迴圈
  7. foreach迴圈
  8. while 迴圈
  9. do while迴圈

布林與布林運算子

布林代數 WIKI

布林運算C# 微軟說明

運算子寫法
大於>
小於<
大於等於>=
小於等於<=
等於==
不等於!=
<>
反向!
AND (條件都成立)&
&&
OR (條件只要一邊成立就可)|
||
表:布林運算

程式語言中,所有的判斷都是靠布林運算在進行,結果只有通過true或不通過false,簡單的說非黑及白。

這邊先簡單看一下,到時候我們if會一起學,先有個印象就好。布林運算在本科中是一門稱為數位邏輯的課程,一學期兩學分,這邊我們只有簡單的帶過。

if 判斷式

if(條件)
{
  //條件成立執行這邊
}
else{
  //條件不成立執行這邊
}

範例

int score = 90;
if(score >= 80)
{
  Console.WriteLine("及格");
}else
{
  Console.WriteLine("不及格,加油好嗎。");
}

if省略else

if(條件)
{
   //條件成立時執行
}

這個作法很常用喔。

範例 a b c 找出最大值與最小值

int a = 50;
int b = 90;
int c = 40;

// 找出最大值
int max = a;
if (b > max)
{
    max = b;
}
if (c > max)
{
    max = c;
}

// 找出最小值
int min = a;
if (b < min)
{
   min = b;
}
if (c < min)
{
   min = c;
}
Console.WriteLine($"最大值: {max}");
Console.WriteLine($"最小值: {min}");

這個題目我在面試時候有遇過,多數是找最大值就好。

省略大跨號{}

if(條件)
   //這邊只能放一行,條件成立時執行

範例

bool open = false;
//其他程式碼
//...
if(open == true)
  door.Open();
//其他程式碼

注意,這樣寫的時候,下面那行要進行縮排(按tab 空四格),這是程式設計界約定成俗的作法。

不過有些公司文化蠻反對這種寫法

巢狀if (nested if) 或稱多層 if

盡量別用超過三層

if(條件1)
{
  if(條件2)
  {
    //條件2成立執行這邊
    if(條件3){    
      //條件3成立執行這邊  
    }else{    
      //條件3不成立執行這邊 
    }    
  }
  else{
    //條件2不成立執行這邊
  }
}
else{
  //條件1不成立執行這邊
}

(⚠️這樣寫實際上很難維護⚠️)

範例

int score = 90;
if(score > 80)
{
  Console.WriteLine("及格");
}
else
{
  if(score > 60){
    Console.WriteLine("不及格,加油好嗎。");
  }
  else
  {
    Console.WriteLine("算了,沒救了。");
  }
}

else if

用法

if(條件1)
{
  //條件1成立執行的程式
}else if(條件2)
{
  //前面的條件不成立,但條件2成立執行的程式
}else if (條件3)
{
  //前面的條件不成立,但條件3成立執行的程式
}else{
  //前面條件都不成立時執行的程式,這個else也可以省略
}

說明:就是用在前次判斷不成立時,就會依序找下一個else if,

範例

int score = 90;

if(score > 80)
{
  //分數>80會執行
  Console.WriteLine("及格");
}else if(score > 60)
{
  // 60 < 分數 > 80
  Console.WriteLine("不及格邊緣。");
}else if(score > 40)
  // 40 < 分數 > 60
  Console.WriteLine("算了,沒救了。");
}else{
  //分數小於等於40
  Console.WriteLine("是在hello");
}

布林值判斷

這邊開始把之前的布林判斷加入,主要講解後面幾個 !(NOT) &&(AND) ||(OR)

複習一下

  1. ! ,NOT運算 ,反相。
  2. && ,AND運算,及,兩者同時成立為True。
  3. || ,OR運算,或,兩者只要一邊成立為True。

註:工程師通常這幾個詞都直接念英文。

&&&的差別,&會對左右兩邊的進行求值,而&&會先對左邊的,如果左邊是True才對右邊的繼續求值,在多數時候可以減少運算次數,所以會直接使用&&

範例

假設

  1. 男生存款>3000萬,天菜,快點跟我結婚。
  2. 男生存款介於2000萬-3000萬,可以交往看看。
  3. 男生存款介於2000萬-3000萬,身高>180,快點跟我結婚。
  4. 其他,保持聯絡

這邊其實要先整理一下邏輯如下,我們要使用else if來解。

  1. 男生存款>=3000萬,天菜,快點跟我結婚。
  2. 男生存款>=2000萬 + 身高>180,快點跟我結婚。
  3. 上面都不成立時,當男生存款>=2000萬,可以交往看看。
  4. 其他,保持聯絡
//個人條件設定
int high = 180;
int money = 1000 * 10000;

if ( money >= (3000 * 10000) )
{
    //存款>=3000萬
    Console.WriteLine("天菜快跟我結婚");
}
else if(money >= (2000 * 10000) && (high >= 180)){    
    Console.WriteLine("天菜快跟我結婚");
}
else if(money >= (2000 * 10000))
{
    //當男生存款>=2000萬
    Console.WriteLine("可以交往看看");
}
else
{
    //不考慮交往
    Console.WriteLine("保持聯絡");
}

inline if

這是以前程式設計就有的神奇寫法,用再簡化if的寫法。

變數 = 條件 ? 條件成立的值 : 條件不成立的值 ;

等同於

if(條件)
{
    變數 = 條件成立的值;
}
else
{
    變數 = 條件不成立的值;
}

範例 判斷分數是否及格

int score = 90 ;
string result = score > 60 ? "及格" : "不及格" ;
Console.WriteLine( $"成績判定結果: {result } ") ;

一開始可能會覺得很難讀,不過這個寫法程式寫久了就會很常用。

範例 判斷基數偶數

int number = 3 ;
string result = (number % 2) == 1 ? "奇數" : "偶數" ;
Console.WriteLine($"數字{number} 為{result}") ;

更多的inline if ,使用它模擬switch或elseif

inline if可以弄成連續多個條件比較

結果 = 條件1 ? 條件1成立 :
       條件2 ? 條件2成立 :
       條件3 ? 條件3成立 :
       條件4 ? 條件4成立 : 
       ......
       :都不成立

範例 分數等級判斷

string result = score > 90 ? "A" :
                score > 80 ? "B" :
                score > 60 ? "C" :
                "D" 
                

Switch Case

這個很像else if ,但參考的條件比較嚴格

我自己其實比較少用switch,通常要用的時候才會查一下。

一般用法

switch (變數)
{
    case 第一個條件:
        //做某件事
        break;
    case 第二個條件:
        //做某件事
        break;
    case 第三個條件:
        //做某件事;
        break;
    default:
        //都不成立時候要做
        break;
}

⚠️注意,每個case後都要加上break; ,代表這個case要執行的程式碼結束。⚠️

範例:

switch (garde)
{
    case "A":
        Console.WriteLine("過於優秀") ;
        break;
    case "B":
        Console.WriteLine("尚可") ;
        break;
    case "C":
        Console.WriteLine("勉勉強強") ;
        break;
    default:
        Console.WriteLine("重修") ;
        break;
}

數值範圍的用法範例

int score = 90;
string grade;
switch (score)
{
    case int n when (n >= 90):
        grade = "A";
        break;
    case int n when (n >= 70):
        grade= "B";
        break;
    case int n when (n >= 60):
        grade =  "C";
        break;
    default:
        grade = "D";
        break;
}
Console.WriteLine($"Score: {score} , Grade: {grade}");
Console.ReadKey();

Array陣列

微軟官方說明

如果要在電腦中輸入很多相同的資料,例如全班的分數,就會使用陣列來做。

型別 變數名稱 = new 型別[長度];
// 定義一個陣列
int[] array1 = new int[5];

// 定義陣列 加上初始值
int[] array2 = [1, 2, 3, 4, 5, 6];

// 定義二維陣列
int[,] multiDimensionalArray1 = new int[2, 3];

// 定義二維陣列,並加上初始值
int[,] multiDimensionalArray2 = { { 1, 2, 3 }, { 4, 5, 6 } };

// 宣告鋸齒陣列
int[][] jaggedArray = new int[6][];

// 定義鋸齒陣列0;
jaggedArray[0] = [1, 2, 3, 4];
  1. 陣列的位置稱為索引(Index)
  2. 陣列索引從0開始。
  3. 陣列有幾個位置稱為陣列長度,取得陣列長度寫法是 numbers.Length();
  4. 讀寫超出陣列索引範圍的程式碼會導致程式掛掉。

C# 宣告陣列

型別 變數名稱 = new 型別[長度];

範例

int[] numbers = new int[5]; // 建立一個數字Array,長度為6
string[] names = new name[8]; //建立一個字串array,長度為9

//初始值
int [] numbers = new int[]{3,6,9,7,2}; //建立一個陣列int[4]

//定義一個星期
string[] weekDays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
Console.WriteLine(weekDays[0]);
Console.WriteLine(weekDays[1]);
Console.WriteLine(weekDays[2]);
Console.WriteLine(weekDays[3]);
Console.WriteLine(weekDays[4]);
Console.WriteLine(weekDays[5]);
Console.WriteLine(weekDays[6]);

C#陣列操作 存入值

陣列名稱[索引] = 值;
int[] numbers = new int[5];
numbers[0] = 9999; //存入999

C# 陣列操作 取值

變數 = 陣列名稱[索引];
int [] numbers = new int[]{3,6,9,7,2}; //建立一個陣列int[4]
int first;
first = numbers[0];
Console.WriteLine($"First of numbers = {first }");

複製陣列 Array.Copy

官方說明 Array.Copy Method (System) | Microsoft Learn

int[] originalArray = new int[5] { 1, 2, 3, 4, 5 };

// 創建一個新陣列,其大小為5
int[] newArray = new int[5];

// 使用Array.Copy來複製元素
Array.Copy(originalArray, newArray, originalArray.Length);

增加陣列大小

陣列大小一旦定義好是無法變更的,所以通常做法是定義一個新的,然後複製原本的過去。

int[] originalArray = new int[5] { 1, 2, 3, 4, 5 };

// 創建一個新陣列,其大小為10
int[] newArray = new int[10];

// 使用Array.Copy來複製元素
Array.Copy(originalArray, newArray, originalArray.Length);

// 現在newArray包含舊陣列的元素並且大小為10

這個大概知道就好,要用的時候再google作法就好。

尋找陣列內的值

通常有三種方法

  1. 用For迴圈
  2. 用IndexlOf
  3. 用Linq

通常用IndexlOf或Linq,看情況,這邊先教IndexOf

使用 IndexOf

注意,這個只能完全比對。

寫法

結果 = Array.IndexOf(陣列,要找的值);

說明: 如果有找到,會回傳所在的Index,如果沒找到回傳-1

int[] array = { 1, 2, 3, 4, 5 };
int valueToFind = 3;
int index = Array.IndexOf(array, valueToFind);

if (index != -1)
{
  Console.WriteLine($"找到了,位置 {index}");
}
else
{
  Console.WriteLine("找不到");
}

// 宣告並初始化字串陣列
string[] array = { "apple", "banana", "cherry", "date", "fig", "grape" };
        
// 要搜尋的字串,這邊要跟陣列內的值一模一樣才找的到。
string valueToFind = "cherry";
        
// 使用 Array.IndexOf 方法搜尋字串
int index = Array.IndexOf(array, valueToFind);
        
// 檢查搜尋結果
if (index != -1)
{
  Console.WriteLine($"找到了,位置 {index}");
}
  else
{
  Console.WriteLine("找不到");
}

取得陣列長度

陣列名稱.Length
//陣列
string[] array = { "apple", "banana", "cherry", "date", "fig", "grape" };

int arrLength = array.Length;

清除陣列內容

直接初始化就好

//陣列
string[] array = { "apple", "banana", "cherry", "date", "fig", "grape" };

// 所有元素都會被設置為預設值空字串
array = new int[array.Length];

排序sort

電腦的排序分兩種

  1. asc 小到大
  2. desc 大到小
//asc 由小排到大
Array.Sort(目標陣列);

//desc 由大排到小
Array.Sort(目標陣列, (x, y) => y.CompareTo(x));

LIST

LIST比起Array靈活非常多,多數工程師比較喜歡用List這個物件。

大概有幾個理由,List可以新增、插入、刪除資料,Array對長度作變動都需要重建Array,但List不能多為度,通常會使用Array是已知資料大小的狀況下,這樣效能會優於List,不過List實在太香了(?)。

List常用的方法

  1. Add() 新增
  2. Remove() 移除特定對象
  3. AddRang() 把另一個List或Array加入這個List
  4. Sum()加總
  5. Avg()平均
  6. Count算有幾個
  7. Any() List裡面有東西會回傳true
  8. Where(n=>n == “值”)

Array轉List

// 宣告並初始化一個整數陣列
int[] array = { 1, 2, 3, 4, 5 };
        
// 使用 List<T> 的建構函數將陣列轉換為列表
List<int> list = new List<int>(array);

//另一個方法(我比較常用)
List<int> list = array.ToList();

建立List與Add() 加入值

List<資料型態> myList = new List<資料型態>();
//或
List<資料型態> myList = new List<資料型態>(){初始值...};

//加入值
myList.Add(資料);

//取值 
變數 = myList[索引];

範例

List<string> students = new List<string>();

//加入
students.Add("Marry");
students.Add("Jake");
students.Add("Harry");


string name;

//取值
name = students[0];

移除特定值 Remove

List<string> students = new List<string> { "孔子", 老子", "莊子", "老黃", "蘇媽" };
 
// 要移除的學生名稱
string studentToRemove = "孔子";

// 移除特定的學生名稱
// 用一個旗標來存是否有成功移除,如果找不到removed = false
bool removed = students.Remove(studentToRemove);

if (removed)
{
  Console.WriteLine($"學生 '{studentToRemove}' 已經被退學");
}
else
{
  Console.WriteLine($"學生 '{studentToRemove}' 查無此人");
}

取得陣列大小 Count

List<string> students = new List<string> { "孔子", 老子", "莊子", "老黃", "蘇媽" };
int count = students.Count;

Console.WriteLine($"向日葵小班共有{Count}個學生");

Loop(迴圈)

微軟官方說明 Iteration statements -for, foreach, do, and while – C# reference | Microsoft Learn

電腦除了計算以外,再來是常用在做重複的事情,稱為迴圈,迴圈有分幾種

  1. for跟foreach
  2. wihile
  3. do while

for loop (for迴圈)

for(int i = 0 ; i < 10 ;i++ )
{
  Console.WriteLine($"i= {i}");
}

Console.WriteLine("執行結束,按任意鍵繼續");
Console.ReadKey();

for範例輸出

說明

int i = 0

設定迴圈初始值,稱為initializer  section

i < 10

迴圈會繼續跑的條件,稱為condition 

i++

每跑完一次會執行這段,稱為step或iterator section

範例1+2+….9+10

int sum = 0;
for(int i = 1 ; i <= 10 ;i++ )
{
  sum = sum + i;
  Console.WriteLine($"i= {i}");
}
Console.WriteLine($"加總結果 sum = {sum}");
Console.WriteLine("執行結束,按任意鍵繼續");
Console.ReadKey();

執行結果

for範例執行結果1加到10

範例 5+7+9+11+…19

int sum = 0;
for(int i = 5 ; i <= 19 ;i+=2 )
{
  sum = sum + i;
  Console.WriteLine($"i= {i}");
}
Console.WriteLine($"加總結果 sum = {sum}");
Console.WriteLine("執行結束,按任意鍵繼續");
Console.ReadKey();

說明:這邊主要關鍵在於step是2,i = i + 2;

輸出結果

for範例輸出結果

範例 反著數,5 4 3 2 1 boom

for(int i = 5 ; i > 0 ;i-- )
{
  Console.WriteLine($"i= {i}");
}
Console.WriteLine($"BOOM!!!");
Console.WriteLine("執行結束,按任意鍵繼續");
Console.ReadKey();

[for範例倒數計時

範例 for 無限迴圈

for(;;)
{
  //無限迴圈要執行的內容
}
string input;
Console.WriteLine("請輸入內容,輸入exit離開");
for (; ;) //如果要迴圈無限執行 可以這樣寫
{
    Console.Write("請輸入:");
    input = Console.ReadLine();   
    
    Console.WriteLine("輸入的內容是:" + input);

    if (input == "exit")
    {
        break; //這是直接結束整個迴圈
    }
}

Console.WriteLine("執行結束,按任意鍵繼續");
Console.ReadKey();

for 無限迴圈

範例 印出陣列內容

int[] numbers = new int[] {5,9,7,10,33,15 };
for (int i = 0; i < numbers.Length; i++)
{
    Console.WriteLine($"numbers [{i}]:{numbers [i]}");
}

for印出陣列內容結果

範例 計算平均

//這邊數字可以改成自己想要的
int[] numbers = new int[] {5,9,7,10,33,15 };
int sum = 0;
for (int i = 0; i < numbers.Length; i++)
{
    sum += numbers[i];
}
Console.WriteLine("總和為:" + sum);
Console.WriteLine("平均為:" + sum / numbers.Length);

Console.WriteLine("執行結束,按任意鍵繼續");
Console.ReadKey();

for計算平均

跳脫迴圈 continue; break;

  1. continue; 跳過這次執行
  2. break ; 跳出整個迴圈

Continues;

跳過這輪for剩下的程式碼

我用一個簡單的範例,假如我要計算1加到100,但是跳過數字50。

int sum = 0;
int skipNumber = 50;
for (int i = 1; i <= 100; i++)
{
    //遇到50時候跳過這輪
    if (i == skipNumber)
    {
        continue;
    }
    sum += i; //等同 sum = sum + i;
}

break;

直接離開迴圈,這個也很常使用。

int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

// 要找的數字
int target = 7;

//紀錄位置
int index = -1;
for (int i = 0; i < numbers.Length; i++)
{
  if (numbers[i] == target )
  {
    index = i;
   
    // 因為已經找到了使用 break 離開整個迴圈
    break;
  }
}
        
Console.WriteLine("尋找完成");

if(index != -1)
{
 Console.WriteLine($"數字 {target} 在索引 {i}");
}else{
 Console.WriteLine($"數字 {target} 不在此陣列");
}

Console.WriteLine("執行結束,按任意鍵繼續");
Console.ReadKey();

範例 計算輸入數字是否為質數

說明:

讓使用者輸入一個數字,由程式判斷是否為質數。
這邊有幾個技巧

  1. 限制使用者輸入的數字要大於等2
  2. 只需要檢查到√n ,例如100只要檢查到10即可,可以大幅縮減需要檢查的數量。
int number;

// 使用 for(;;) 迴圈,不斷提示使用者輸入,直到輸入有效的整數
for (; ; )
{
    // 提示使用者輸入一個數字
    Console.WriteLine("請輸入一個大於或等於2的數字:");

    // 讀取使用者輸入到number,然後記錄能否正常轉型
    bool isValid = int.TryParse(Console.ReadLine(), out number);

    // 檢查輸入是否有效且大於或等於2
    if (isValid && number >= 2)
    {
        break; // 跳出迴圈
    }

    // 如果輸入無效,提示錯誤訊息
    Console.WriteLine("輸入錯誤。請重新輸入一個有效的整數,且必須大於或等於2。");
}

// 判斷該數字是否為質數
bool isPrime = true;

for (int divisor = 2; divisor <= Math.Sqrt(number); divisor++)
{
    // 如果 number 能被 divisor 整除,則 number 不是質數
    if (number % divisor == 0)
    {
        //非質數則跳出迴圈
        isPrime = false;
        break;
    }
}

// 顯示結果
if (isPrime)
{
    Console.WriteLine($"{number} 是質數。");
}
else
{
    Console.WriteLine($"{number} 不是質數。");
}

// 等待使用者按下任意鍵後結束程式
Console.WriteLine("按下任意鍵結束...");
Console.ReadKey();

foreach 迴圈

foreach迴圈是for迴圈的簡易版,如果你是需要逐一取出陣列內容,使用foreach會比for好寫,而且效率會好上一些。

foreach(var item in 陣列)
{
   //對item做一些事
}

範例

List<string> students = new List<string>();
students.Add("馬克");
students.Add("店小二");
students.Add("蛋頭");

Console.WriteLine("學生名單");
int i = 1;
foreach (var student in students)
{
    Console.WriteLine($"{i}. {student}");
    i++;
}

// 等待使用者按下任意鍵後結束程式
Console.WriteLine("按下任意鍵結束...");
Console.ReadKey();

image

while迴圈跟do wile迴圈

話說這兩個在生涯中其實很少用到,通常都用for + if 直接替代就好,do whilewhile差別是while會先檢查條件是不是符合,do while則是先執行{}內的程式碼一次再檢查

while迴圈

while(執行條件)
{
  //條件成立執行
}
//無限迴圈
while(true)
{
  
}

範例 1+2+3+4+5

int sum = 0;
int number = 1;

while (number <= 5) 
{
    Console.WriteLine($"sum = {sum} number = {number }");
    sum += number;
    number++;
    Console.WriteLine($"sum = {sum} number = {number }");
    Console.WriteLine($"------------------------------");//分隔線
}
Console.WriteLine($"迴圈結束");
Console.WriteLine($"sum = {sum} number = {number}")

// 等待使用者按下任意鍵後結束程式
Console.WriteLine("按下任意鍵結束...");
Console.ReadKey();
image

do while迴圈

do
{
}while(繼續執行條件)

範例 選擇要執行的功能

Console.WriteLine("請輸入要執行的功能(1~4),或按下 q 離開程式");
Console.WriteLine("1. 九九乘法表");
Console.WriteLine("2. 計算 1+2+3+...+n");
Console.WriteLine("3. 計算 1+3+5+...+n");
Console.WriteLine("4. 計算 1+1/2+1/3+...+1/n");
selectFunction = Console.ReadLine();

switch (selectFunction)
{
    case "1":
        Console.WriteLine("執行九九乘法表");
        //相關程式
        break;
    case "2":
        Console.WriteLine("計算 1+2+3+...+n");
        //相關程式
        break;
    case "3":
        Console.WriteLine("計算 1+3+5+...+n");
        //相關程式
        break;
    case "4":
        Console.WriteLine("計算 1+1/2+1/3+...+1/n");
        //相關程式
        break;
    case "q":
        Console.WriteLine("離開程式");
        break;
    default:
        Console.WriteLine("輸入錯誤,請重新輸入");
        break;
    }
} while (selectFunction != "q");

// 等待使用者按下任意鍵後結束程式
Console.WriteLine("按下任意鍵結束...");
Console.ReadKey();

綜合範例 跟電腦剪刀石頭布

輸入 1= 剪刀 ,2 = 石頭 ,3= 布

電腦隨機出拳

// 宣告選項
string[] options = { "剪刀", "石頭", "布" };
        
//輸入
Console.WriteLine("請輸入你的選擇: 1= 剪刀, 2= 石頭, 3= 布");
int playerChoice;

//判斷輸入有沒有問題
bool isValid = int.TryParse(Console.ReadLine(), out playerChoice);
        
if (!isValid || playerChoice < 1 || playerChoice > 3)
{
  Console.WriteLine("無效的輸入。請輸入1, 2或3。");
  return;
}

// 減去1以符合陣列索引
playerChoice--;

// 電腦隨機出拳
// 回傳 0-2
Random random = new Random();
int computerChoice = random.Next(0, 3);

// 顯示玩家和電腦的選擇
Console.WriteLine($"你選擇了: {options[playerChoice]}");
Console.WriteLine($"電腦選擇了: {options[computerChoice]}");

// 判斷勝負,先處理平手部分
if (playerChoice == computerChoice)
{
  Console.WriteLine("平手!");
}
//只要判斷玩家贏的狀況
else if ((playerChoice == 0 && computerChoice == 2) || // 剪刀贏布
         (playerChoice == 1 && computerChoice == 0) || // 石頭贏剪刀
         (playerChoice == 2 && computerChoice == 1))   // 布贏石頭
{
  Console.WriteLine("你贏了!");
}
else //其他都是電腦贏的狀況
{
  Console.WriteLine("你輸了!");
}

0 條留言

提交留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *