如何打印二维数组中的行数



我正在用C#编写,并试图对打印数组中的行进行编号。我不知道如何打印二维数组。

它是这样写的:

第0####行

第1#######行

第2#######行

int[,] array1 = new int[6, 6]
{
{10, 20, 10, 20, 21, 99 },
{2, 27, 5, 45, 20, 13 },
{17, 20, 20, 33, 33, 20 },
{21, 35, 15, 54, 20, 37 },
{31, 101, 25, 55, 26, 66 },
{45, 20, 44, 12, 55, 98 }
};
int Length = array1.GetLength(0);
int Height = array1.GetLength(1);
Console.WriteLine("  Col 0  Col 1  Col 2  Col 3  Col 4  Col 5");
for (int i = 0; i < Length; i++)
{
for (int j = 0; j < Height; j++)
{
Console.Write(string.Format("{0,6} ", array1[i, j]));
}
Console.Write("n" + "n");
}
Console.ReadKey();

您只需在打印数组行的值之前向控制台写入即可。

int[,] array1 = new int[6, 6]
{
{10, 20, 10, 20, 21, 99 },
{2, 27, 5, 45, 20, 13 },
{17, 20, 20, 33, 33, 20 },
{21, 35, 15, 54, 20, 37 },
{31, 101, 25, 55, 26, 66 },
{45, 20, 44, 12, 55, 98 }
};
int Length = array1.GetLength(0);
int Height = array1.GetLength(1);
Console.WriteLine("  Col 0  Col 1  Col 2  Col 3  Col 4  Col 5");
for (int i = 0; i < Length; i++)
{
Console.Write("Row {0} ", i); // Outside of the loop :)
for (int j = 0; j < Height; j++)
{
Console.Write(string.Format("{0,6} ", array1[i, j]));
}
Console.Write("n" + "n");
}
Console.ReadKey();

您想在第一个循环内写入Row 0Row 1等,但在第二个循环外写入,应该使用Console.Write(),而不是Console.WriteLine()

var array1 = new int[6, 6]
{
{10, 20, 10, 20, 21, 99 },
{2, 27, 5, 45, 20, 13 },
{17, 20, 20, 33, 33, 20 },
{21, 35, 15, 54, 20, 37 },
{31, 101, 25, 55, 26, 66 },
{45, 20, 44, 12, 55, 98 }
};
int Length = array1.GetLength(0);
int Height = array1.GetLength(1);
for (var i = 0; i < Length; i++)
{
Console.Write("Row {0} : ", i);
for (var j = 0; j < Height; j++)
{
Console.Write("{0,6} ", array1[i, j]);
}
Console.WriteLine();
}

注意每个外循环迭代结束时的Console.WriteLine(),它将在下一次迭代之前带您到一条新行。

输出

行0:10 20 10 20 21 99

第1行:2 27 5 45 20 13

第2行:17 20 20 33 33 20

第3行:21 35 15 54 20 37

第4行:31 101 25 55 26 66

第5行:45 20 44 12 55 98