← 從零開始學 C#
第 21 課,共 39 課 · 10 XP
陣列
理論與題目說明
機器翻譯,尚未經母語人士審閱。
陣列是固定長度、同一型別元素的集合:
int[] scores = { 10, 25, 7 };
string[] names = new string[3]; // 3 個 null
scores[0] = 15; // 索引從 0 開始
Console.WriteLine(scores.Length); // 3
foreach (int s in scores) Console.WriteLine(s);
超出範圍會引發 IndexOutOfRangeException(而不是像 C 那樣默默弄壞記憶體)。
System 裡方便的東西:
Array.Sort(scores); // 遞增,就地排序
Array.Reverse(scores);
int max = scores.Max(); // 需要 using System.Linq;
int[,] grid = new int[3, 4]; // 二維:grid[y, x]
長度不能改——要改就用 List<T>(using System.Collections.Generic;)。
題目。 第一行是 n,第二行是用空白分隔的 n 個整數。用空白分隔、依遞增順序輸出它們,
下一行以小數點後 1 位輸出平均值。