我在 C# 中有一個多維陣列,我通過捕獲用戶的輸入分配了矩陣的索引,我正在嘗試實作一個條件結構,它可以讓我在單獨的行上列印矩陣的每一行,例如例如,如果我的陣列是 A 并且 A 的維度為 3 x 3,則代碼在第一行列印前三個元素,在下一行列印接下來的三個元素,依此類推。我試圖實作這一點,因為將結構理解為普通矩陣會更容易,并且還可以使用錯誤的操作構建整個矩陣類。
代碼
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 個元素并且它是一個方陣,那么每行包含三個元素都列印在一行上。
uj5u.com熱心網友回復:
我會使用這樣的輸出:
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列印換行符)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/385971.html
