如何在新行中打印矩阵(多维数组)的行
how to print the row of a matrix(multi-dimensional array) in a new line
我在 C# 中有一个多维数组,我通过捕获用户的输入分配了矩阵的索引,我正在尝试实现一个条件结构,它可以让我打印矩阵的每一行一个单独的行,例如,如果我的数组是 A 并且 A 的维度为 3 x 3,那么代码将在第一行打印前三个元素,在下一行打印接下来的三个元素,依此类推。我正在努力实现这一目标,因为这样可以更容易地将结构理解为普通矩阵,并且还可以通过错误的操作构建整个矩阵 class。
代码
class Matrix{
static int[,] matrixA;
static void Main(string[] args){
Console.WriteLine("Enter the order of the matrix");
int n = Int32.Parse(Console.ReadLine());
matrixA = new int[n, n];
//assigning the matrix with values from the user
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
matrixA[i, j] = Int32.Parse(Console.ReadLine());
}
}
//the code below tries to implement a line break after each row for the matrix
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if( (n-1-i) == 0)
{
Console.Write("\n");
}
else
{
Console.Write(matrixA[i, j].ToString() + " ");
}
}
}
}
}
如何修改我的代码,以便如果数组有 9 个元素并且它是一个方矩阵,那么包含三个元素的每一行都打印在一行上。
我会使用这样的输出:
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(matrixA[i, j].ToString() + " ");
}
Console.Write("\n");
}
当内部循环完成时,这意味着一行已被完全打印。所以那是唯一需要换行符的时候。 (n
次外循环 ==> n
换行打印)。
我在 C# 中有一个多维数组,我通过捕获用户的输入分配了矩阵的索引,我正在尝试实现一个条件结构,它可以让我打印矩阵的每一行一个单独的行,例如,如果我的数组是 A 并且 A 的维度为 3 x 3,那么代码将在第一行打印前三个元素,在下一行打印接下来的三个元素,依此类推。我正在努力实现这一目标,因为这样可以更容易地将结构理解为普通矩阵,并且还可以通过错误的操作构建整个矩阵 class。
代码
class Matrix{
static int[,] matrixA;
static void Main(string[] args){
Console.WriteLine("Enter the order of the matrix");
int n = Int32.Parse(Console.ReadLine());
matrixA = new int[n, n];
//assigning the matrix with values from the user
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
matrixA[i, j] = Int32.Parse(Console.ReadLine());
}
}
//the code below tries to implement a line break after each row for the matrix
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if( (n-1-i) == 0)
{
Console.Write("\n");
}
else
{
Console.Write(matrixA[i, j].ToString() + " ");
}
}
}
}
}
如何修改我的代码,以便如果数组有 9 个元素并且它是一个方矩阵,那么包含三个元素的每一行都打印在一行上。
我会使用这样的输出:
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(matrixA[i, j].ToString() + " ");
}
Console.Write("\n");
}
当内部循环完成时,这意味着一行已被完全打印。所以那是唯一需要换行符的时候。 (n
次外循环 ==> n
换行打印)。