C#學習 陣列(22)

huiy_小溪發表於2024-11-14

建立陣列

string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
int[] myNum1 = {10, 20, 30, 40};
int[] myNum2 = new int[4]{10, 20, 30, 40};
int[] myNum3 = new int[]{10, 20, 30, 40};
int[] myNum4 = new int[4];
myNum4[0]=10;
myNum4[1]=20;
myNum4[2]=30;
myNum4[3]=40;

訪問: 索引從0開始

myNum4[0]; // 10

迴圈

string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.Length; i++) 
{
  Console.WriteLine(cars[i]);
}
foreach(string s in cars){
   Console.WriteLine(s); 
}

排序

Array.Sort(cars);

函式

myNum4.Max(); // 最大值
myNum4.Min(); // 最小值
myNum4.Sum(); // 求和
myNum4.Average(); // 平均值

建立多維陣列

int[,] myNum5 =
{
    { 1, 2, 3, 4 },
    { 10, 20, 30, 40 },
};

訪問多維陣列元素

myNum5[0,0]; // 1
myNum5[1,3]; // 40

相關文章