[C#]数组(二维数组,交错数组)
一、二维数组
定义举例:
'''
int[,] b = { { 1, 1 }, { 3, 4 } };
'''
'''
int[,] c = new int[3, 3]{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8 , 9 } };
'''
'''
int[,] d = new int[, ]{ { 1, 2, 3 }, { 4, 5, 6 } };
'''
若赋值定义分开可以这样做
'''
int[,] v;
v = new int[2,3];
'''
和一维数组不同,二维数组的输出的值是4,而且不能用这种遍历
'''
Console.Write (b.Length);
'''
将二维数组的行和列转换,并赋值给另一个二维数组:
'''
int[,] c = new int[2, 3]{ { 1, 2, 3 }, { 4, 5, 6 } };
int[,] d = new int[3, 2];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
d [i, j] = c [j, i];
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
Console.Write (" {0}", d [i, j]);
}
Console.WriteLine ();
}
'''
求对角线元素之和
'''
int[,] a = { { 10, 12, 13 }, { 14, 15, 16 }, { 17, 18, 19 } };
int sum = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == j) {
sum += a [i, i];
}
}
}
Console.WriteLine (sum);
'''
二、交错数组
数组里面放数组的感觉
定义:
'''
int[] a = {1,2,3}, b = {4,5,6}, c = {7,8,9};
int[][] numbers = new int[3][];
int[][] number = new int[3][]{a,b,c};
int[][] number1 = new int[4][]{a,b,c,new int[]{4,9}};
'''
输出:
'''
int x = number [1] [1];
Console.WriteLine (x);
'''
遍历输出:
'''
for (int i = 0; i < number1.Length; i++) {
for (int j = 0; j < number1 [i].Length; j++) {
Console.Write (" {0}", number1 [i] [j]);
}
Console.WriteLine ();
}
//1 2 3
//4 5 6
//7 8 9
//4 9
'''