2012-10-10 14 views
14

Tengo una matriz 2D de la siguiente manera:matriz de impresión 2D en formato de matriz

long[,] arr = new long[4, 4] {{ 0, 0, 0, 0 }, 
           { 1, 1, 1, 1 }, 
           { 0, 0, 0, 0 }, 
           { 1, 1, 1, 1 }}; 

Quiero imprimir los valores de esta matriz en formato matricial como:

0 0 0 0 
1 1 1 1 
0 0 0 0 
1 1 1 1 

¿Cómo puedo hacer esto ?

Respuesta

23

Usted puede hacerlo de esta manera (con una gama ligeramente modificada para mostrar que funciona para matrices no cuadradas):

 long[,] arr = new long[5, 4] { { 1, 2, 3, 4 }, { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; 

     int rowLength = arr.GetLength(0); 
     int colLength = arr.GetLength(1); 

     for (int i = 0; i < rowLength; i++) 
     { 
      for (int j = 0; j < colLength; j++) 
      { 
       Console.Write(string.Format("{0} ", arr[i, j])); 
      } 
      Console.Write(Environment.NewLine + Environment.NewLine); 
     } 
     Console.ReadLine(); 
+0

Thnx Mark, me ayudó .. – iCoder4777

+1

En lugar de "\ n" podría usar Environment.NewLine, esto es recomendado y siempre funciona –

+0

@ Nick: tienes razón, ejemplo de código modificado. – markmuetz

3

así:

long[,] arr = new long[4, 4] { { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 0, 0, 0, 0 }, { 1, 1, 1, 1 } }; 

var rowCount = arr.GetLength(0); 
var colCount = arr.GetLength(1); 
for (int row = 0; row < rowCount; row++) 
{ 
    for (int col = 0; col < colCount; col++)    
     Console.Write(String.Format("{0}\t", arr[row,col])); 
    Console.WriteLine(); 
} 
+0

necesita a izquierda-pad números de modo que las columnas alinee – LeffeBrune

+0

Eso no pondrá espacios entre los dígitos. – Bobson

+2

Su ejemplo no se compila en mi computadora en VS2010 –

0

Tu lo puede hacer como este en pocas manos.

 int[,] values=new int[2,3]{{2,4,5},{4,5,2}}; 

     for (int i = 0; i < values.GetLength(0); i++) 
     { 
      for (int k = 0; k < values.GetLength(1); k++) { 
       Console.Write(values[i,k]); 
      } 

      Console.WriteLine(); 
     } 
+0

¿Qué pasa con los espacios entre el elemento de la matriz. Esto hace para diferenciar filas. – baymax

0

Aquí es cómo hacerlo en Unidad:

(respuesta Modificado de @markmuetz así que asegúrese de upvote his answer)

int[,] rawNodes = new int[,] 
{ 
    { 0, 0, 0, 0, 0, 0 }, 
    { 0, 0, 0, 0, 0, 0 }, 
    { 0, 0, 0, 0, 0, 0 }, 
    { 0, 0, 0, 0, 0, 0 }, 
    { 0, 0, 0, 0, 0, 0 } 
}; 

private void Start() 
{ 
    int rowLength = rawNodes.GetLength(0); 
    int colLength = rawNodes.GetLength(1); 
    string arrayString = ""; 
    for (int i = 0; i < rowLength; i++) 
    { 
     for (int j = 0; j < colLength; j++) 
     { 
      arrayString += string.Format("{0} ", rawNodes[i, j]); 
     } 
     arrayString += System.Environment.NewLine + System.Environment.NewLine; 
    } 

    Debug.Log(arrayString); 
}